DanInDC DanInDC - 2 years ago 137
Java Question

Merge (Concat) Multiple JSONObjects

I am consuming some JSON from two different sources, I end up with two

s and I'd like to combine them into one.


"Object1": {
"ArrayKey": [Data0, Data1]

"Object2": {

Code, using http://json.org/java/ library:

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

So in this situation I'd like to combine
, either to make a totally new
or concat one to the other. Any ideas besides pulling them all apart and individually adding in by

Answer Source

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

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

This would be a lot easier if JSONObject implemented Map, and supported putAll.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download