小编典典

合并(Concat)Java中的多个JSONObject

json

我从两个不同的来源使用了一些JSON,最后得到两个JSONObjects,我想将它们组合为一个。

数据:

"Object1": {
    "Stringkey":"StringVal",
    "ArrayKey": [Data0, Data1]
}

"Object2": {
    "Stringkey":"StringVal",
    "Stringkey":"StringVal",
    "Stringkey":"StringVal",
}

使用http://json.org/java/库的代码:

// jso1 and jso2 are some JSONObjects already instantiated
JSONObject Obj1 = (JSONObject) jso.get("Object1");
JSONObject Obj2 = (JSONObject) jso.get("Object2");

因此,在这种情况下,我想将Obj1和组合在一起Obj2,以制作一个全新的产品JSONObject或彼此结合。除了将它们拉开并分别加puts
之外,还有其他想法吗?


阅读 1772

收藏
2020-07-27

共1个答案

小编典典

如果要使用两个键Object1和Object2创建新对象,则可以执行以下操作:

JSONObject Obj1 = (JSONObject) jso1.get("Object1");
JSONObject Obj2 = (JSONObject) jso2.get("Object2");
JSONObject combined = new JSONObject();
combined.put("Object1", Obj1);
combined.put("Object2", Obj2);

如果要合并它们,例如顶级对象有5个键(Stringkey1,ArrayKey,StringKey2,StringKey3,StringKey4),我认为您必须手动执行此操作:

JSONObject merged = new JSONObject(Obj1, JSONObject.getNames(Obj1));
for(String key : JSONObject.getNames(Obj2))
{
  merged.put(key, Obj2.get(key));
}

如果JSONObject实现Map,并支持putAll,这会容易得多。

2020-07-27