Merge (Concat) Multiple JSONobjects in Java

Merge (Concat) Multiple JSONObjects in Java

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.

Concat two json objects in java

Do something like this:

List<String> array = new ArrayList<String>();
array.add("{\"message\":\"test\",\"status\":\"0\"}");
array.add("{\"message\":\"test-2\",\"status\":\"1\"}");
array.toString();

If you want to user support for JSON object in Java, consider using Gson:

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

public class Main {

public static void main(String[] args) {
JsonObject json1 = (JsonObject) new JsonParser().parse("{\"message\":\"test\",\"status\":\"0\"}");
JsonObject json2 = (JsonObject) new JsonParser().parse("{\"message\":\"test-2\",\"status\":\"1\"}");
JsonArray array = new JsonArray();
array.add(json1);
array.add(json2);
System.out.println(array.toString());
}
}

This would give you what you want this time using objects.

Java: Merging two json objects together with primary key

My Java is a little rusty but I would use a map.

List<JSONObject> objectsA = ... ;
List<JSONObject> objectsB = ... ;

Map entries = new HashMap<String, JSONObject>();
List<JSONObject> allObjects = new ArrayList<JSONObject>();
allObjects.addAll(objectsA);
allObjects.addAll(objectsB);

for (JSONObject obj: allObjects) {
String key = obj.getString("id");
JSONObject existing = entries.get(key);
if (existing == null) {
existing = new JSONObject();
entries.put(key, existing);
}

for (String subKey : obj.keys()) {
existing.put(subKey, obj.get(subKey));
}
}

List<JSONObject> merged = entries.values();

This is more efficient than two nested loops and there's still room for improvement.

EDIT: References to external documentation and related answers.

  • http://docs.oracle.com/javase/7/docs/api/java/util/Map.html
  • http://www.json.org/javadoc/org/json/JSONObject.html
  • https://stackoverflow.com/a/2403427/937006

which is the best way to merge two JSONObject(org.json) object in java

public static void main(String...strings) throws JSONException {
String s1 = "{\"a\":\"1\",\"b\":\"2\"}";
String s2 = "{\"c\":\"4\",\"d\":[{}]}";

JSONObject jsonObject1 = new JSONObject(s1);
JSONObject jsonObject2 = new JSONObject(s2);

Iterator itr = jsonObject2.keys();

while(itr.hasNext()) {
String key = (String) itr.next();
jsonObject1.put(key, jsonObject2.get(key));
}

System.out.println(jsonObject1.toString());

}

Output : {"a":"1","b":"2","c":"4","d":[{}]}

Another way assuming you have simple JSON data as u have shown in the example

public static void main(String...strings) throws JSONException {
String s1 = "{\"a\":\"1\",\"b\":\"2\"}";
String s2 = "{\"c\":\"4\",\"d\":[{}]}";

int firstIndex = s2.indexOf("{");
int lastIndex = s1.lastIndexOf("}");

String result = s1.substring(0, lastIndex)+"," + s2.substring(firstIndex+1);
System.out.println(result);

JSONObject jsonObject = new JSONObject(result);

Iterator iterator = jsonObject.keys();
while (iterator.hasNext()) {
String key = (String) iterator.next();
System.out.println("Key :: "+key+" value :: "+jsonObject.get(key));
}
}

output :: {"a":"1","b":"2","c":"4","d":[{}]} Key :: a value :: 1 Key
:: b value :: 2 Key :: c value :: 4 Key :: d value :: [{}]

Merge two JSONs to JSONObject instead of JSONArray

I prefer and recommend use Gson from Google:

The last release is 2.8.6 from Oct of 2019:

<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.6</version>
</dependency>

Always check last version on Maven Central Repository:

  • https://mvnrepository.com/artifact/com.google.code.gson/gson

Example:

public static void mergeJSONs() {
String JSON1 = "{\"1level1\":{\"1level2\":{\"1label1\":\"1value1\"}}}";
String JSON2 = "{\"1level1\":{\"1level2\":{\"1label2\":\"1value2\"}}}";
String JSON3 = "{\"2level1\":{\"2level2\":{\"2level3\":{\"2label1\":\"2value1\"}}}}";
String JSON4 = "{\"2level1\":{\"2level2\":{\"2label2\":\"2value2\"}}}";
String finalJson = organizeJson(JSON1, JSON2, JSON3, JSON4);
System.out.println(finalJson);
}

The method can receive a list of json payloads, add a root element and merge:

public String organizeJson(String... jsonList) throws Exception {
JsonObject jsonObj = null;
Gson gson = new GsonBuilder().setPrettyPrinting().create();
for (String json : jsonList) {
if (jsonObj != null) {
jsonObj = jsonMerge(jsonObj, gson.fromJson(json, JsonObject.class));
} else {
jsonObj = gson.fromJson(json, JsonObject.class);
}
}
JsonObject jsonStringsRoot = new JsonObject();
/* Add "strings" as root element */
jsonStringsRoot.add("strings", jsonObj);
return gson.toJson(jsonStringsRoot);
}

Method using recursive call to find the last level on nested objects (deep merge):

public static JsonObject jsonMerge(JsonObject jsonA, JsonObject jsonB) throws Exception {
for (Map.Entry<String, JsonElement> sourceEntry : jsonA.entrySet()) {
String key = sourceEntry.getKey();
JsonElement value = sourceEntry.getValue();
if (!jsonB.has(key)) {
if (!value.isJsonNull()) {
jsonB.add(key, value);
}
} else {
if (!value.isJsonNull()) {
if (value.isJsonObject()) {
jsonMerge(value.getAsJsonObject(), jsonB.get(key).getAsJsonObject());
} else {
jsonB.add(key, value);
}
} else {
jsonB.remove(key);
}
}
}
return jsonB;
}


Reference:

  • https://stackoverflow.com/a/38757661/5626568


Related Topics



Leave a reply



Submit