我想从另一个json对象中的这个json对象解析所有“name”和“desc”。我需要另一个“为”?
{
"main": {
"details": [
{
"owner_name": "owner_name1",
"id": "id1",
"details2": {
"data": [
{
"name": "name1",
"desc": "my desc1",
},
{
"name": "name2",
"desc": "my desc2",
}
],
}
},
{
"owner_name": "owner_name2",
"id": "id2",
"details2": {
"data": [
{
"name": "name3",
"desc": "my desc3",
},
{
"name": "name4",
"desc": "my desc4",
}
]
}
}
]
}
}
和我的java代码是:
JSONObject jsono = new JSONObject(data);
JSONObject mainObject = jsono.getJSONObject("main");
JSONArray jsonArray = mainObject.getJSONArray("details");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object1 = jsonArray.getJSONObject(i);
JSONObject objectDetails2 = object1.getJSONObject("details2");
JSONArray jsonArrayData = objectDetails2.getJSONArray("data");
for (int j = 0; j < jsonArrayData.length(); j++) {
JSONObject object = jsonArrayData.getJSONObject(j);
Actors actor = new Actors();
actor.setName(object.getString("name"));
actor.setDesc(object.getString("desc"));
actorsList.add(actor);
}
它只显示详细信息内的第一个“数据”结果2未显示数据内部的第二个详细信息。 现在我的结果是:“name1,dmy desc1,name2,my desc2”
我希望所有结果如:“name1,dmy desc1,name2,我的desc2,name3,我的desc3,name4,我的desc4”
答案 0 :(得分:3)
我如何再次进入对象和数组?我需要来自&#34; name&#34;的详细信息。 和&#34; desc&#34;
从details2
JSONObject获取object
,然后获取data
JSONArray:
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
// get details2 JSONObject
if(object.has("details2")){
if(!object.isNUll("details2")){
JSONObject objectDetails2 = object.getJSONObject("details2");
// get data JSONArray from objectDetails2
if(objectDetails2.has("data")){
if(!objectDetails2.isNUll("data")){
JSONArray jsonArrayData = objectDetails2.getJSONArray("data");
// iterate to jsonArrayData
for (int j = 0; j < jsonArrayData.length(); j++) {
JSONObject objectInner = jsonArray.getJSONObject(j);
String strName=objectInner.optString("name");
....
}
}else{
// details2 found but null
}
}else{
// details2 not found
}
}else{
// details2 found but null
}
}else{
// details2 not found
}
}
答案 1 :(得分:0)
我认为你应该像这样进入“details2”JSON对象:
JSONArray jsonArrayData=object.getJSONObject("details2").getJSONArray("data");
答案 2 :(得分:0)
您必须首先获取对象,然后解析它以获取不同的名称和信息
JSONArray jsonArrayData;
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject("details");
jsonArrayData=object.getJSONArray("data");
for(int k=0;k<jsonArrayData.length();k++)
{
Actors actor = new Actors();
actor.setName(object.getString("name"));
actor.setDesc(object.getString("desc"));
actorsList.add(actor);
}
}
我建议您使用GSON,它使用起来非常简单,