碰到類似如下格式的json,總是解析失敗,希望大神幫助解析一下
{
"code":0,
"message":"",
"data":[
{
"info":{"id":0,"name":"lina","age":10},
"subclass":[]
},
{
"info":{"id":1,"name":"may","age":16},
"subclass":[
{
"info":{"id":2,"name":"aa","age":13},
"subclass":[]
},
{
"info":{"id":3,"name":"bb","age":12},"subclass":[]
}
]
}
]
}
給你個小例子,你可以這樣一層一層解下去:
public static void main(String[] args) {
String jsonStr = "{\"code\":0,\"message\":\"\",\"data\":[{\"info\":{\"id\":0,\"name\":\"lina\",\"age\":10},\"subclass\":[]},{\"info\":{\"id\":1,\"name\":\"may\",\"age\":16},\"subclass\":[{\"info\":{\"id\":2,\"name\":\"aa\",\"age\":13},\"subclass\":[]},{\"info\":{\"id\":3,\"name\":\"bb\",\"age\":12},\"subclass\":[]}]}]}";
JSONObject jobj = JSONObject.fromObject(jsonStr);
if(null != jobj && jobj.has("code")){
System.out.println("code:" + jobj.getInt("code"));
}
if(null != jobj && jobj.has("message")){
System.out.println("message:" + jobj.getString("message"));
}
if(null != jobj && jobj.has("data")){
JSONArray ja = jobj.getJSONArray("data");
for(int i = 0; i < ja.size(); i++){
System.out.println(
ja.getJSONObject(i).getJSONObject("info").getInt("id")
+ " " + ja.getJSONObject(i).getJSONObject("info").getString("name")
+ " " + ja.getJSONObject(i).getJSONObject("info").getInt("age"));
}
}
}
我做例子的時候用的是 net.sf.json.JSONObject 不過它們大體都是相同的,你可以作為參考。