Search code examples
javajsonjackson

Merging Two JSON Documents Using Jackson


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 Google and Jackson's documentation but couldn't find anything.


Solution

  • 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.