JSON解析一定要掌握的两条规则:
1.如果看到是{ }–>使用JSONObject
2.如果看到的[ ]–>使用JSONArray解析
比如说我们要解析的数据如下:
{
"code":200,
"msg":"正常返回",
"result":{
"data":[
{
"teacher":[
{
"parentId":0,
"subType":39,
"content":"亲近自然,喜欢探究",
"time":0,
"content2":null,
"ave":0
},
{
"parentId":0,
"subType":40,
"content":"具有初步的探究能力",
"time":0,
"content2":null,
"ave":1
}
],
"parent":[
{
"parentId":0,
"subType":39,
"content":"亲近自然,喜欢探究",
"time":0,
"content2":null,
"ave":0
}
]
}
],
"count":1,
"totalnum":1,
"pindex":0
}
}
开始解析:
import org.json.JSONArray;
import org.json.JSONObject;
public class Test01 {
public static void main(String[] args) {
String json = "{\"code\":200,\"msg\":\"正常返回\",\"result\":{\"data\":"
+ "[{\"teacher\":[{\"parentId\":0,\"subType\":39,\"content\":\"亲近自然,喜欢探究\",\"time\":0,\"content2\":null,\"ave\":0.0},"
+ "{\"parentId\":0,\"subType\":40,\"content\":\"具有初步的探究能力\",\"time\":0,\"content2\":null,\"ave\":1.0}],"
+ "\"parent\":[{\"parentId\":0,\"subType\":39,\"content\":\"亲近自然,喜欢探究\",\"time\":0,\"content2\":null,\"ave\":0.0}"
JSONObject jsonline = JSONObject.fromObject(json);
//如果看到是{ }–>使用JSONObject,这里是"result":{}
JSONObject jsonresult = jsonline.getJSONObject("result");
//如果看到的[ ]–>使用JSONArray解析,这里是"data":[]
JSONArray jsondata = jsonresult.getJSONArray("data");
//如果看到是{ }–>使用JSONObject,这里是{}
JSONObject data = jsondata.getJSONObject(0);
//如果看到的[ ]–>使用JSONArray解析,这里是"teacher":[]
JSONArray teacher = data.getJSONArray("teacher");
for(int i = 0;i < teacher.size(); i++){
//多组数据
JSONObject obj = teacher.getJSONObject(i);
//obj.getString("content")是获取元素
System.out.println(obj.getString("content"));
}
System.out.println(teacher);
}
}