1

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.

TryHard
  • 359
  • 2
  • 3
  • 15
  • 1
    How about check answer of this question in below link? [Merge/Extend JSON Objects using Gson in Java](https://stackoverflow.com/questions/34092373/merge-extend-json-objects-using-gson-in-java/52621962#52621962) – Han Feb 21 '20 at 09:27
  • If you don not need to do it explicitly in Java you can use jq to do it in terminal: https://stedolan.github.io/jq/ – Hakan Dilek Feb 21 '20 at 09:27
  • @HakanDilek I need to use it in my java programm. Do you have another solution? – TryHard Feb 21 '20 at 09:47
  • @Han Do you know a way to do this in Jackson? – TryHard Feb 21 '20 at 09:51
  • 1
    Please don't keep asking similar/same questions. This sort of thing is not allowed on this site. – Hovercraft Full Of Eels Feb 22 '20 at 23:17

1 Answers1

2

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"}}

Vikas
  • 6,868
  • 4
  • 27
  • 41
  • Does this work for more complex json structures too? I want to merge multiple trees which have arrays and objects – TryHard Feb 21 '20 at 11:33
  • The solution is specific to the json in the question. But you can use the same approach for complex objects as well. – Vikas Feb 21 '20 at 11:36
  • Is there an easy way to do this? I want to do this but it does not really work: https://stackoverflow.com/questions/60328050/build-a-json-tree-with-recursion/ – TryHard Feb 21 '20 at 12:16