简体   繁体   English

合并 JSON 树 Jackson

[英]Merge JSON Tree Jackson

I want to merge two JSON trees with jackson.我想将两个 JSON 树与 jackson 合并。

JSONTree1: JSONTree1:

{"test":{"test1":"test1"}}

JSONTree2: 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"}} {"test":{"test1":"test1","test2":"test2"}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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