合并(Concat)Java中的多个JSONObjects [英] Merge (Concat) Multiple JSONObjects in Java
问题描述
我从两个不同的来源消费了一些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
或彼此连接.除了将它们拉开并按put
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)Java中的多个JSONObjects的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!