JSONObject和JSONArray遍历数组与对象

JSONObject和JSONArray的API链接:
http://json-lib.sourceforge.net/apidocs/jdk15/net/sf/json/JSONObject.html
http://json-lib.sourceforge.net/apidocs/net/sf/json/JSONArray.html

1、识别json格式字符串是JSONObject还是JSONArray

JSON数据格式只有两种形式,分别是:

1
2
{ "key" : "value" } //JSONObject(对象)
[{ "key1" : "value1" }, { "key2" : "value2" }] //JSONArray(数组)

JSONObject可以用key取值,JSONArray只能遍历取值

2、遍历json数组

假设我们得到的json字符串result如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
{
    "feature" : "fresh_today" ,
    "photos" :[
       {
          "id" : 40581634 ,
          "name" : "Dandelion 5"
       },
       {
          "id" : 40581608 ,
          "name" : "Dandelion 3"
       }
    ]
}

可以看出来,最外面是个json对象,photos节点是个数组,遍历代码如下:

1
2
3
4
5
6
7
8
9
10
11
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
 
JSONObject jsonObject = JSONObject.fromObject(result);
String feature = jsonObject.getString( "feature" );
JSONArray photoArray = jsonObject.getJSONArray( "photos" );
for ( int i = 0 ; i < photoArray.size(); i++) {
     JSONObject object = (JSONObject) photoArray.get(i);
     int id = object.getInt( "id" );
     String name = object.getString( "name" );
}

附上一个很好用的在线json格式化和校验的网站:http://jsonformatter.curiousconcept.com/

本文链接地址:http://www.javathing.com/use-jsonobject-and-jsonarray-read-json/


你可能感兴趣的:(java基础)