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"
}]
我想'topologyInfo.add(tempobj);'并在循环中创建新的'JSONObject'实例。 –
我们如何使用JSONArray的add? –
将JSONObject添加到JSONArray不会克隆它,但是您正在多次编写** same **对象,并在此对象引用的每个循环步骤中替换“id”。 –