json 的解析-使用Android中的JSONObject和JSONArray解析json数据,gson中的JsonReader解析json数据...

关于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().equals("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 block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值