3

I have a class (Jackson annotations/getters/setters/etc are omitted):

public class Sample {
   public String name;
   public Integer value;
}

I have an instance, e.g.:

Sample sample = new Sample("one", null),

and i have a json string:

{"name" = "two", "value" = 3}

And i update the object with json:

ObjectMapper mapper = new ObjectMapper();
mapper.readerForUpdating(sample).readValue(json);

After updating my object looks like this:

[Sample: name = "two", value = 3]

But i need do not overwrite not null fields, as the name is, so my object after updating would looks like this:

 [Sample: name = "one", value = 3]

Unfortunally, i can't edit my class and Jackson annotations, so i need to change somehow a config of my mapper. Is threre a way to do it?

coolsv
  • 268
  • 3
  • 17

1 Answers1

2

The idea behind the readerForUpdating method is not to create a new instance of the object,just to replace the values of the passed object into the object for update.

I had the same problem ,wanted to replace ONLY the values that are not null,but to do that I needed to isolate the ObjectMapper and configure it to not transfer null values ,which combined with the readerForUpdating method does what we want:

public static void updateModels(Object original,Object data) {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false);

    try {
        objectMapper.readerForUpdating(original).readValue(objectMapper.writeValueAsBytes(data));
    } catch (IOException e) {
        e.printStackTrace();
    }
}
Georgi Peev
  • 912
  • 1
  • 14
  • 25