Saturday, March 29, 2014

Gson how to parse Json array types


Heroes who, finding just learning Android, encounter a problem: Gson how to parse an array of type Json

Array types like:

{
"Count": 100,
"Page": 1,
"List": [{
"Title": "I",
"Tel": "110"
},
{
"Title": "you",
"Tel": "120"
}]
}

I do not know how to resolve this type of Json with gson, expect heroes have urged, it is best to have the code! Thank you!
<-! Main posts under Banner (D4) -><-! Posts under the main text (D5) ->
Reply:
No need to use Gson
JSONObject jsonObject = new JSONObject (String); this json data into an object.
Then JSONArray jsonArray = jsonObject.getJSONArray ("list"); obtain list data inside
for (int i = 0; i {
JSONObject jsonOb = (JSONObject) jsonArray.opt (i);
int tel = jsonOb.getInt ("tel");
}
Intermediate data read cycle
Reply:
 String json = "{start: 0, pageCount: 2, dataList: [{\" STRPRODUCTCODE \ ": \" DWJ100 \ ", \" STRVERSIONXZTEXT \ ": \" Initial installation package \ ", \" STRPRODUCTNAME \ ": \" Foreign Trade Enquiry System \ ", \" STRVERSIONTYPE \ ": \" 10 \ ", \" STRVERSIONID \ ": \" V1 \ ", \" STRVERSIONCODE \ ": \" 1.0.2.1018 \ ", \" LINE_NUM \ ": 1, \" STRVERSIONXZ \ ": \" 10 \ ", \" LIMIT \ ": 1, \" NUMSHOWORDER \ ": 1, \" STRVERSIONLOG \ ": \" fix a bug, increased 2 function \ ", \" STRVERSIONTYPETEXT \ ": \" Standard \ ", \" DATRELEASEDATE \ ": \" 2013-9-28 10:47:26 \ ", \" STRVERSIONFY \ ": \" 100,000 yuan \ ", \" STRSUPPORTOS \ ": \" Windows 2003/Windows 2008 \ ", \" STRDELFLG \ ": \" 0 \ "}" + 
", {\" STRPRODUCTCODE \ ": \" DWJ100 \ ", \" STRVERSIONXZTEXT \ ": \" Initial installation package \ ", \" STRPRODUCTNAME \ ": \" Foreign Trade Enquiry System \ ", \" STRVERSIONTYPE \ ": \ "10 \", \ "STRVERSIONID \": \ "V1 \", \ "STRVERSIONCODE \": \ "1.0.2.1018 \", \ "LINE_NUM \": 1, \ "STRVERSIONXZ \": \ "10 \ ", \" LIMIT \ ": 1, \" NUMSHOWORDER \ ": 1, \" STRVERSIONLOG \ ": \" fix a bug, increased 2 function \ ", \" STRVERSIONTYPETEXT \ ": \" Standard \ " , \ "DATRELEASEDATE \": \ "2013-9-28 10:47:26 \", \ "STRVERSIONFY \": \ "10 万 人民币 \", \ "STRSUPPORTOS \": \ "Windows 2003/Windows 2008 \ ", \" STRDELFLG \ ": \" 0 \ "}" +
"]}";
Gson gson = new Gson ();
JsonParser parser = new JsonParser ();
List > list = new ArrayList > ();
. JsonObject jsonObject = parser.parse (json) getAsJsonObject ();
JsonArray jsonArray = jsonObject.getAsJsonArray ("dataList");
Type type = new TypeToken > () {} getType ();.
for (int i = 0; i JsonElement el = jsonArray.get (i);
Map tmp = gson.fromJson (el, type);
list.add (tmp);
System.out.println (tmp.get ("STRPRODUCTCODE"));
}
jsonObject.remove ("dataList");
jsonObject.add ("dataList", parser.parse (gson.toJson (list)) getAsJsonArray ().);
System.out.println (gson.toJson (jsonObject));

No comments:

Post a Comment