2017-12-18 90 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,但你簡單地複製它的參考。