JSONArray构建不正确

时间:2017-12-18 11:15:14

标签: java

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,其名称为Stack,id为1,2& 3。在我的JSONArray中,3个对象与"id" 3对齐 我的最终结果应该是

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

但是我得到了

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

2 个答案:

答案 0 :(得分:4)

这里的问题是你在for循环的每次迭代中重用相同的JSONObject,所以你要覆盖“id”值。

尝试克隆对象......

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);
    }
}

答案 1 :(得分:1)

您每次迭代都会覆盖相同的属性'id' JSONObject#put确实引用了Map界面。

那是因为:

JSONObject tempobj = topoInfo;

您没有处理新的JSONObject,但您只是复制它的参考资料。