原文地址:http://my.eoe.cn/iceskysl/archive/19629.html?f=nge
在 Android 中解析JSON很方便,但是 JSON 的格式或者层级各有不同,搞的有人好像就是不能入门,那我就简单写下~
标准的 json 格式一般是这样的
1 2 3 4 5 6 7 8 9 10 11 |
{ "background" : "true",
"expires" : "3600000",
"items" : [{
"author" : "vincent4j",
"created_at" : "2013-05-05T13:14:38+08:00",
"id" : 512},
{
"author" : "vincent4j",
"created_at" : "2013-05-05T13:14:38+08:00",
"id" : 512}]
}
|
那么其最外层的是个 {} ,也就是其是个 JSON 对象,直接转成JSONObject,再看 items 这个下面是个 [] ,也就是个数组,那么直接getJSONArray就可以得到了,代码如下:
1 2 3 4 5 6 7 8 9 |
JSONObject josnObject = new JSONObject(str);
JSONArray array = josnObject.getJSONArray("items");
int length = array.length();
for (int i = 0; i < length; i++) {
JSONObject object = array.getJSONObject(i);
//Do your code
Log.v("json object", object.getString("id"));
}
|
上面这个是最常见的格式了,但是有的时候你会遇到这样的 json 格式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
{ "response" : { "items" : [ { "detail_url" : "http://api.eoe.cn/client/blog?k=show&id=3348",
"head_image_url" : "http://www.eoeandroid.com/uc_server/avatar.php?uid=739935&size=small",
"id" : "3348",
"name" : "过期的白砂糖",
"short_content" : "GitHub上最火的40个Android开源项目(一)GitHub上最...",
"time" : "1367809230",
"title" : "GitHub上最火的40个Android开源项目(一)"
},
{ "detail_url" : "http://api.eoe.cn/client/blog?k=show&id=18229",
"head_image_url" : "http://www.eoeandroid.com/uc_server/avatar.php?uid=2&size=small",
"id" : "18229",
"name" : "iceskysl",
"short_content" : "OS X Mavericks新功能介绍: https://help.apple.com/o...",
"time" : "1382471844",
"title" : "修改DNS大幅提高OS X Mavericks(5.29G)升级下载速度(4.1M/s)"
}]
}
}
|
看到区别了没,多了一层,那我们就可以这样来调
1 2 3 4 5 6 7 8 9 |
JSONObject josnObject = new JSONObject(str);
JSONObject responseObject = josnObject.getJSONObject("response");
JSONArray array = responseObject.getJSONArray("items");
int length = array.length();
for (int i = 0; i < length; i++) {
JSONObject object = array.getJSONObject(i);
//Do your code
Log.v("json object", object.getString("id"));
}
|
总结一句话:
获取节点内容的时候,遇到{}就getJSONObject,遇到[]就getJSONArray~