2013-04-24 168 views
0

我有兩個具有相同鍵但不同值的JsonObject。 我想合併兩個JsonObject與另一個JsonObject中的同一個鍵。具有相同鍵和不同值的兩個JsonObject的合併

JSONObject a = new JSONObject("{\"data\": [ {\"empId\": 1,\"deptId\": 2},{\"empId\": 3,\"deptId\": 4}]}"); 
JSONObject b = new JSONObject("{\"data\": [ {\"empId\": 7,\"deptId\": 8},{\"empId\": 9,\"deptId\": 10}]}"); 

結果應該是這樣的。

{\"data\": [ {\"empId\": 1,\"deptId\": 2},{\"empId\": 3,\"deptId\": 4},{\"empId\": 7,\"deptId\": 8},{\"empId\": 9,\"deptId\": 10}]} 

請讓我知道如何做到這一點。

+1

你想要結果是什麼? – 2013-04-24 09:37:24

+1

目前還不清楚你想要什麼結果。請提供對象'c',這是'a'和'b'合併的結果。 – pfyod 2013-04-24 09:38:30

+0

我編輯了這個問題,添加了結果JsonObject應該如何。感謝您的回覆。 – user2261222 2013-04-24 09:54:03

回答

3

使用JSONArray存儲多個JSONObject。使用這個不需要擔心爲這個JSONObject例如

JSONObject a = new JSONObject("{\"data\": [ {\"empId\": 1,\"deptId\": 2},{\"empId\": 3,\"deptId\": 4}]}"); 
JSONObject b = new JSONObject("{\"data\": [ {\"empId\": 7,\"deptId\": 8},{\"empId\": 9,\"deptId\": 10}]}"); 

編輯

JSONArray jArr_A= a.getJSONArray("data"); 

JSONArray jArr= new JSONArray(); 
for(int i=0;i<jArr_A.length();i++){ 
    jArr.put(jArr_A.getJSONObject(i)); 
} 

現在另一個對象

jArr_A= b.getJSONArray("data"); 

for(int i=0;i<jArr_A.length();i++){ 
    jArr.put(jArr_A.getJSONObject(i)); 
} 

現在檢查jArr對象的長度有它的兩倍。

JSONObject mainJson = new JSONObject(); 
mainJson.put("data", jArr); 
+0

請編輯一些我無法獲取代碼格式工具 – Pratik 2013-04-24 09:44:50

+0

感謝您的回覆,但我從兩個不同的地方獲得JsonObjects具有相同的鍵,但值是不同的對象列表。所以我想要在新的JsonObject中合併具有相同給定鍵的對象列表。 – user2261222 2013-04-24 10:00:47

+0

嗨請檢查更新的答案 – Pratik 2013-04-24 10:34:09

相關問題