Merging Two JSON Documents Using Jackson

前端 未结 6 2243
有刺的猬
有刺的猬 2020-11-29 22:51

Is it possible to merge two JSON documents with the Jackson JSON library? I am basically using the Jackson mapper with simple Java Maps.

I\'ve tried to search in Goo

6条回答
  •  一向
    一向 (楼主)
    2020-11-29 23:33

    One way is to use ObjectReader like so:

    MyBean defaults = objectMapper.readValue(defaultJson, MyBean.class);
    ObjectReader updater = objectMapper.readerForUpdating(defaults);
    MyBean merged = updater.readValue(overridesJson);
    

    which will combine data from two sources. This only makes a shallow copy, i.e. does not do recursive merge on contained objects.

    Otherwise you may need to just read JSON as a tree (JsonNode), loop over contents and merge manually. This often makes sense anyway since rules of merging are not trivial, and everyone has their own ideas of how merging should work.

    EDIT: (03-Apr-2017)

    As per @Fernando Correia's comment, there is actually a new feature added in upcoming Jackson 2.9 (to be released in April or May 2017) that does allow deep merging, finally.

提交回复
热议问题