[转载]解析json – penink – 博客园.
关于Json:http://www.json.org/
Json解析库gson: http://code.google.com/p/google-gson/
1.使用Android中的JSONObject和JSONArray解析json数据
String strJson = "{\"students\":[{\"name\":\"Jack\",\"age\":12}, {\"name\":\"Vista\",\"age\":23}, {\"name\":\"Kaka\",\"age\":22}, {\"name\":\"Hony\",\"age\":31}]}";try {JSONObject jo = new JSONObject(strJson);JSONArray jsonArray = (JSONArray) jo.get("students");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数据
try {String string = "{\"class\":1, \"students\":[{\"name\":\"jack\", \"age\":21},{\"name\":\"kaka\", \"age\":21},{\"name\":\"lucy\", \"age\":21}]}";StringReader sr = new StringReader(string);JsonReader jr = new JsonReader(sr);jr.beginObject();if (jr.nextName().contains("class")) {System.out.println("班级: " + jr.nextString());if (jr.nextName().equals("students")) {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) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}
本文介绍了两种常用的JSON解析方式:一是利用Android内置的JSONObject和JSONArray进行解析;二是通过gson库中的JsonReader来读取和解析JSON数据。这两种方法适用于不同的场景,并提供了具体的代码示例。

445

被折叠的 条评论
为什么被折叠?



