Gson是一種物件的解析json,很好用,介紹一個網站http://www.php.cn/可以幫我們看一個字串是不是Json
*&*對於Json檔案{ "id" : "3232", "data" : { "data1" : { "name" : "xiaoming", "age" : "12" } } }
如果用Gson來解析的話,就要定義與這個json節點對應的類,我們用MyData來表示解析完的json對象,Data來代表解析完data節點的對象,Data1類別來代表data1節點的對象
public class MyData { int <strong>id</strong>; Data <strong>data</strong>; } public class Data { Data1 <strong>data1</strong>; } public class Data1 { String <strong>name</strong>; String <strong>age</strong>; }
注意,成員變數的名字一定要跟節點的名字一樣(加粗的字元)
public void parseAssertData() { InputStream is = null; try { is = this.getAssets().open("ss.json", Context.MODE_PRIVATE); int length = is.available(); byte[] buffer = new byte[length]; is.read(buffer); String temp = new String(buffer); Reader response = new StringReader(temp.toString()); Gson gson = new Gson(); MyData mydata = gson.fromJson(response,MyData.class); System.out.println("===age="+mydata.data.data1.age); } catch (IOException ex) { ex.printStackTrace(); } }