Reputation: 379
I want to merge two JSON trees with jackson.
JSONTree1:
{"test":{"test1":"test1"}}
JSONTree2:
{"test":{"test2":"test2"}}
Output:
{"test":{"test1":"test1", "test2":"test2"}}
Is there an easy method in jackson which does this? I cant find one. Thanks for your help.
Upvotes: 1
Views: 601
Reputation: 7175
You can achieve it with jackson as below,
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> json1 = mapper.readValue("{\"test\":{\"test1\":\"test1\"}}", Map.class);
Map<String, Object> json2 = mapper.readValue("{\"test\":{\"test2\":\"test2\"}}", Map.class);
Map result = new HashMap<>();
json1.forEach((k,v)->json2.merge(k, v, (v1, v2)->
{
Map map = new HashMap<>();
map.putAll((Map) v1);
map.putAll((Map) v2);
result.put(k, map);
return v2;
} ));
String resultJson = new ObjectMapper().writeValueAsString(result);
System.out.println(resultJson);
Result:
{"test":{"test1":"test1","test2":"test2"}}
Upvotes: 2