我需要通过递归来解析这个json ..
{
"code": "200",
"data": [
{
"id": "2",
"name": "BE",
"parent": "0",
"children": [
{
"id": "3",
"name": "Computer Science",
"parent": "2",
"children": [
{
"id": "4",
"name": "1st Year",
"parent": "3",
"children": [
{
"id": "8",
"name": "A",
"parent": "4",
"children": []
},
{
"id": "9",
"name": "B",
"parent": "4",
"children": []
}
]
},
{
"id": "5",
"name": "2nd Year",
"parent": "3",
"children": [
{
"id": "10",
"name": "A",
"parent": "5",
"children": []
},
{
"id": "11",
"name": "B",
"parent": "5",
"children": []
}
]
},
{
"id": "6",
"name": "3rd Year",
"parent": "3",
"children": [
{
"id": "12",
"name": "A",
"parent": "6",
"children": []
},
{
"id": "13",
"name": "B",
"parent": "6",
"children": []
}
]
},
{
"id": "7",
"name": "4th Year",
"parent": "3",
"children": [
{
"id": "14",
"name": "A",
"parent": "7",
"children": []
},
{
"id": "15",
"name": "B",
"parent": "7",
"children": []
}
]
}
]
}
]
},
{
"id": "16",
"name": "ME",
"parent": "0",
"children": []
},
{
"id": "17",
"name": "Btech",
"parent": "0",
"children": []
}
]
}
答案 0 :(得分:1)
我还没有尝试过,但从逻辑上说它应该是这样的:
public void solve(JSONArray dataArray){
try {
for(int i = 0; i < dataArray.length(); i++) {
JSONObject dataObj = dataArray.getJSONObject(i);
System.out.println(dataObj.getString("id"));
System.out.println(dataObj.getString("name"));
System.out.println(dataObj.getString("parent"));
JSONArray childArray = dataObj.getJSONArray("children");
solve(childArray);
}
} catch(Exception e) {
e.printStackTrace();
}
}
答案 1 :(得分:0)
try
{
JSONObject json=new JSONObject("response");
JSONArray dataArray = json.getJSONArray("data");
for(int i=0;i<dataArray.length();i++)
{
JSONObject dataObj=dataArray.getJSONObject(i);
System.out.println(dataObj.getString("id"));
System.out.println(dataObj.getString("name"));
System.out.println(dataObj.getString("parent"));
JSONArray childArray=dataObj.getJSONArray("children");
for(int j=0;j<childArray.length();j++)
{
JSONObject childObj=childArray.getJSONObject(j);
System.out.println(childObj.getString("id"));
System.out.println(childObj.getString("name"));
System.out.println(childObj.getString("parent"));
}
}
}
catch(Exception e)
{
e.printStackTrace();
}