JSONObject和JSONArray遍历数组与对象

时间:2021-08-03 19:17:01


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/