0

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"
}
2
  • what the final outcome you are expecting ? Commented Oct 17, 2018 at 4:00
  • Question updated Commented Oct 17, 2018 at 4:04

2 Answers 2

2

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);
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks but is there a way to do it without converting to map
There is no other way. This is the best you can do.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.