简体   繁体   中英

Merge JSON Tree Jackson

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM