String str = "[{name:'a',value:'aa'},{name:'b',value:'bb'},{name:'c',value:'cc'},{name:'d',value:'dd'}]" ; // 一个未转化的字符串
if(json.size()>0){ for(int i=0;i<json.size();i++){ JSONObject job = json.getJSONObject(i); // 遍历 jsonarray 数组,把每一个对象转成 json 对象 System.out.println(job.get("name")+"=") ; // 得到 每个对象中的属性值 }}
JSONObject jsonObject = new JSONObject(jsonString); Iterator iterator = jsonObject.keys();while(iterator.hasNext()){ key = (String) iterator.next(); value = jsonObject.getString(key);}
SONArray jsonArray;
jsonArray = JSONArray.fromObject(data);
for(int i=0;i<jsonArray.size();i++){
Object object=jsonArray.get(i);
JSONObject jsonObject=JSONObject.fromObject(object);
String parentId=jsonObject.getString("id");
Integer orderNo1=i;
service.updateParentId(parentId, orderNo1.toString(), "0");
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"
}
[{
"key1"
:
"value1"
}, {
"key2"
:
"value2"
}]
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/