组合(合并)2个JSONObjects的最佳方法是什么?

jim*_*zer 14 java android json

合并(合并)两个的最佳方法是什么JSONObjects

JSONObject o1 = {
    "one": "1",
    "two": "2",
    "three": "3"
}
JSONObject o2 = {
        "four": "4",
        "five": "5",
        "six": "6"
    }
Run Code Online (Sandbox Code Playgroud)

结合而产生o1o2必须

JSONObject result = {
        "one": "1",
        "two": "2",
        "three": "3",
        "four": "4",
        "five": "5",
        "six": "6"
    }
Run Code Online (Sandbox Code Playgroud)

Vit*_*ile 12

我有同样的问题:我找不到putAll方法(并没有在官方参考页面中列出).

所以,我不知道这是否是最好的解决方案,但肯定它运作得很好:

//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));
}
Run Code Online (Sandbox Code Playgroud)

现在,合并的JSONObject存储在 mergedObj


Nir*_*iya 3

像这样将 json 对象合并到新的 json 对象中。

    JSONObject jObj = new JSONObject();
    jObj.put("one", "1");
    jObj.put("two", "2");
    JSONObject jObj2 = new JSONObject();
    jObj2.put("three", "3");
    jObj2.put("four", "4");


    JSONParser p = new JSONParser();
    net.minidev.json.JSONObject o1 = (net.minidev.json.JSONObject) p
                        .parse(jObj.toString());
    net.minidev.json.JSONObject o2 = (net.minidev.json.JSONObject) p
                        .parse(jObj2.toString());

    o1.merge(o2);

    Log.print(o1.toJSONString());
Run Code Online (Sandbox Code Playgroud)

现在 o1 将是合并后的 json 对象。你会得到这样的输出::

{"three":"3","two":"2","four":"4","one":"1"}
Run Code Online (Sandbox Code Playgroud)

请参考此链接并下载 smartjson 库..这是链接http://code.google.com/p/json-smart/wiki/MergeSample

希望它会有所帮助。