What is the best way to combine (merge) 2 JSONObjects?

后端 未结 5 1392
梦毁少年i
梦毁少年i 2021-02-19 02:14

What is the best way to combine (merge) two JSONObjects?

JSONObject o1 = {
    \"one\": \"1\",
    \"two\": \"2\",
    \"three\": \"3\"
}
JSONObject         


        
5条回答
  •  一个人的身影
    2021-02-19 03:19

    I have your same problem: I can't find the putAll method (and it isn't listed in the official reference page).

    So, I don't know if this is the best solution, but surely it works quite well:

    //I assume that your two JSONObjects are o1 and o2
    JSONObject mergedObj = new JSONObject();
    
    Iterator i1 = o1.keys();
    Iterator i2 = o2.keys();
    String tmp_key;
    while(i1.hasNext()) {
        tmp_key = (String) i1.next();
        mergedObj.put(tmp_key, o1.get(tmp_key));
    }
    while(i2.hasNext()) {
        tmp_key = (String) i2.next();
        mergedObj.put(tmp_key, o2.get(tmp_key));
    }
    

    Now, the merged JSONObject is stored in mergedObj

提交回复
热议问题