合并(Concat)多个JSONObjects [英] Merge (Concat) Multiple JSONObjects
问题描述
我从两个不同的来源消耗了一些JSON,我最终得到了两个 JSONObject
,我想将它们组合成一个。
I am consuming some JSON from two different sources, I end up with two JSONObject
s and I'd like to combine them into one.
数据:
"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
,要么将其连接到另一个。任何想法,除了把它们分开并单独加入把
s?
So in this situation I'd like to combine Obj1
and Obj2
, either to make a totally new JSONObject
or concat one to the other. Any ideas besides pulling them all apart and individually adding in by put
s?
推荐答案
如果你想要一个带有两个键Object1和Object2的新对象,你可以这样做:
If you want a new object with two keys, Object1 and Object2, you can do:
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),我想你必须手动完成:
If you want to merge them, so e.g. a top level object has 5 keys (Stringkey1, ArrayKey, StringKey2, StringKey3, StringKey4), I think you have to do that manually:
JSONObject merged = new JSONObject(Obj1, JSONObject.getNames(Obj1));
for(String key : JSONObject.getNames(Obj2))
{
merged.put(key, Obj2.get(key));
}
如果JSONObject实现了地图,支持putAll。
This would be a lot easier if JSONObject implemented Map, and supported putAll.
这篇关于合并(Concat)多个JSONObjects的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!