Reputation: 31
I have two JSON objects like
{
"key1":"value1",
"key2":"value2",
"key3":"value3",
"key4":"value4"
}
and
{
"key2":"value1",
"key4":"value2",
"key6":"value3",
"key8":"value4"
}
I want to merge these two JSON objects into single Json
object without iterating through each key and the final result should be
{
"key1":"value1",
"key2":"value1",
"key3":"value3",
"key4":"value2",
"key6":"value3",
"key8":"value4"
}
Upvotes: 0
Views: 138
Reputation: 136
Consider using a library that does this job for you, like JSON Merge, available at Maven Central.
You will get the desired result with a single line of code:
JSONObject result = new JsonMerger<>(JSONObject.class).merge(json2, json1);
Note: the first JSON parameter passed to the merge
method will always have more precedence/importance than the second one in case of key collisions.
This library works with Jackson, Gson, and other JSON providers as well.
Upvotes: 0
Reputation: 3424
Use any Json Mapper (e.g Jackson) convert json to Map.
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> map = mapper.readValue(json, new TypeReference<Map<String, String>>(){})
once you get two maps like this you can merge them
Map<String, Object> mergedMap = new HashMap<>();
mergedMap.putAll(map1);
mergedMap.putAll(map2);
String json = mapper.writeValueAsString(mergedMap);
Upvotes: 2