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

时间:2013-10-24 12:33:33

标签: java android json

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

JSONObject o1 = {
    "one": "1",
    "two": "2",
    "three": "3"
}
JSONObject o2 = {
        "four": "4",
        "five": "5",
        "six": "6"
    }

合并o1o2的结果必须是

JSONObject result = {
        "one": "1",
        "two": "2",
        "three": "3",
        "four": "4",
        "five": "5",
        "six": "6"
    }

5 个答案:

答案 0 :(得分:11)

我遇到同样的问题:我找不到putAll方法(official reference page中未列出该方法。)

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

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

现在,合并的JSONObject存储在mergedObj

答案 1 :(得分: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());

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

{"three":"3","two":"2","four":"4","one":"1"}

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

希望它会有所帮助。

答案 2 :(得分:0)

这个怎么样:

            Iterator iterator = json2.keys();
            while(iterator.hasNext()){
                String key = iterator.next().toString();
                json1.put(key,map.optJSONObject(key));
            }

答案 3 :(得分:0)

合并JsonObject(gson)-

JsonObject data = new JsonObject();
data = receivedJsoData.get("details").getAsJsonObject();

JsonObject data2 = new JsonObject();
data2 = receivedJsoData1.get("details").getAsJsonObject();

JsonObject mergedData = new JsonObject();

Set<Map.Entry<String, JsonElement>> entries = data1.entrySet();  //will return members of your object
for (Map.Entry<String, JsonElement> entry : entries) {
    mergedData.add(entry.getKey(), entry.getValue());
}
Set<Map.Entry<String, JsonElement>> entries1 = data2.entrySet();  //will return members of your object
for (Map.Entry<String, JsonElement> entry : entries1) {
    mergedData.add(entry.getKey(), entry.getValue());
}

答案 4 :(得分:-1)

试试这个..希望有所帮助

JSONObject result = new JSONObject();
result.putAll(o1);
result.putAll(O2);