2017-12-18 100 views
-1
JSONArray topologyInfo = new JSONArray(); 
String[] ids = {"1","2","3"}; 
JSONObject topoInfo = readTaskLog(); //returns an object like {Name:"Stack"} 
if (topoInfo != null) { 
    for (String id : ids) { 
     JSONObject tempobj=topoInfo; 
     tempobj.put("id", id)); 
     topologyInfo.put(tempobj); 
    } 
} 

我需要3和一个JSONObjects与名称堆栈和id为1,2 & 3.在我的JSONArray 3个对象与"id" 3 我的最终结果应该是像JSONArray不正确构建

[{ 
    "Name": "Stack", 
    "id": "1" 
}, 
{ 
    "Name": "Stack", 
    "id": "2" 
}, 
{ 
    "Name": "Stack", 
    "id": "3" 
}] 

但是我却越来越为

[{ 
    "Name": "Stack", 
    "id": "3" 
}, 
{ 
    "Name": "Stack", 
    "id": "3" 
}, 
{ 
    "Name": "Stack", 
    "id": "3" 
}] 
+0

我想'topologyInfo.add(tempobj);'并在循环中创建新的'JSONObject'实例。 –

+0

我们如何使用JSONArray的add? –

+1

将JSONObject添加到JSONArray不会克隆它,但是您正在多次编写** same **对象,并在此对象引用的每个循环步骤中替换“id”。 –

回答

4

这里的问题是,你是重用相同的JSONObject在for循环的每次迭代,所以你要重写的“ID” v ALUE。

尝试复制而不是对象...

JSONArray topologyInfo = new JSONArray(); 
String[] ids = {"1","2","3"}; 
JSONObject topoInfo = readTaskLog(); //returns an object like {Name:"Stack"} 
if (topoInfo != null) { 
    for (String id : ids) { 
     JSONObject tempobj=new JSONObject(topoInfo.toString()); 
     tempobj.put("id", id)); 
     topologyInfo.put(tempobj); 
    } 
} 
+0

JSONObject.getNames(topoInfo) - >在这里抛出一个错误 –

+0

另一种方法是使用JSONObject tempobj = new JSONObject(topoInfo.toString());但这可能性不如 – PillHead

+0

您也可以从头开始创建JSONObject,并使用JSONObject#元素插入'id'和'name'键/值对。 – LppEdd

1

你覆盖了相同的属性'id'每次迭代。
JSONObject#put确实指的是Map接口。

这是因为:

JSONObject tempobj = topoInfo; 

你不处理一个新JSONObject,但你简单地复制它的参考。