6

The most generic way to convert from JSON to Java objects is to capture the JSON as a Map<String, Object>. From this (or directly) I can convert to a POJO easily:

User user = objectMapper.convertValue(jsonMap, User.class);

Any User fields that were not present in the original JSON will be set to their default values. While this is great for creating new objects (in response to (say) an API call), it doesn't work for updating a POJO.

What I want to achieve is to update an existing User object from incoming JSON using Jackson. This means:

  1. Properties in the incoming JSON (that are also fields in the POJO) are used to update (overwrite) the corresponding fields in the POJO.
  2. Properties in the incoming JSON that are not fields in the POJO are ignored.
  3. Fields in the User POJO that don't have any corresponding properties in the incoming JSON are left alone.

Is this possible with Jackson?

markvgti
  • 4,321
  • 7
  • 40
  • 62
  • you could create a map from your initial user, then merge it with the one from json and at last create a new `User` from the merged map – Lino Aug 13 '21 at 12:50
  • Have a look at [`json-patch`](https://github.com/java-json-tools/json-patch) – Michał Krzywański Aug 13 '21 at 12:51
  • 1
    The Jackson [ObjectMapper](https://fasterxml.github.io/jackson-databind/javadoc/2.7/com/fasterxml/jackson/databind/ObjectMapper.html) has a factory method [readerForUpdating](https://fasterxml.github.io/jackson-databind/javadoc/2.7/com/fasterxml/jackson/databind/ObjectMapper.html#readerForUpdating(java.lang.Object)) that should do this (I didn't test it, but from the API I would suggest that it's what you need). Also see [this answer](https://stackoverflow.com/a/9912406/8178842) for reference. – Tobias Aug 13 '21 at 12:52

1 Answers1

5

You can use readerForUpdating to create an ObjectReader

Factory method for constructing ObjectReader that will update given Object (usually Bean, but can be a Collection or Map as well, but NOT an array) with JSON data.

and then use the readValue on the ObjectReader:

Method that binds content read from given JSON string, using configuration of this reader. Value return is either newly constructed, or root value that was specified with withValueToUpdate(Object).

in a code similar to this one:

  ObjectReader objectReader = objectMapper.readerForUpdating(objectToUpdate);
  MyType objectUpdated = objectReader.readValue(inputJson);
Davide Lorenzo MARINO
  • 26,420
  • 4
  • 39
  • 56