Adnroid解析Json數(shù)組DEMO實(shí)例
需要用到的Json解析庫(kù)Gson請(qǐng)自行解決
下面我們來(lái)看下具體用法
1、使用Android中的JSONObject和JSONArray解析json數(shù)據(jù)
String strJson = "{\"UrlName\":[{\"name\":\"jsons.cn\",\"age\":2}, {\"name\":\"Json工具\(yùn)",\"age\":2}]}"; try { JSONObject jo = new JSONObject(strJson); JSONArray jsonArray = (JSONArray) jo.get("UrlName"); for (int i = 0; i < jsonArray.length(); i) { JSONObject o = (JSONObject) jsonArray.get(i); System.out.println("name:" o.getString("name") "," "age:" o.getInt("age")); } } catch (JSONException e) { e.printStackTrace(); }2、使用Gson中的JsonReader解析json數(shù)據(jù)
try { String string = "{\"Root\":1, \"UrlName\":[{\"name\":\"Jsons.cn\", \"age\":2},{\"name\":\"Json解析\", \"age\":2}]}"; StringReader sr = new StringReader(string); JsonReader jr = new JsonReader(sr); jr.beginObject(); if (jr.nextName().equals("Root")) { System.out.println("最高級(jí)別: " jr.nextString()); if (jr.nextName().equals("UrlName")) { jr.beginArray(); while (jr.hasNext()) { jr.beginObject(); if (jr.nextName().equals("name")) System.out.print("姓名:" jr.nextString()); if (jr.nextName().equals("age")) { System.out.println(" , 年齡:" jr.nextInt()); } jr.endObject(); } jr.endArray(); } } jr.endObject(); } catch (FileNotFoundException e) { e.printStackTrace(); }
原文鏈接:Adnroid解析Json數(shù)組實(shí)例