Update only null values using objectMapper "readerForUpdating"

192 views
Skip to first unread message

Senthil Nathan

unread,
Dec 14, 2022, 8:35:59 PM12/14/22
to jackson-user
Hi, 

Rather updating all the properties, I want to update the values for only null fields using readerForUpdating.

Class:
@Getter
@Setter
public class Record {
     public String source;
     public String resource;
}

Record record = new Record();
record.setSource("sourceFromObject");
record.setResource(null);

Json:

String json = {"source": "sourceFromJson", "resource":"resourceFromJson"}

When I do,
  ObjectMapper objectMapper = new ObjectMapper();
  objectMapper.readerForUpdating(record).readValue(json);

am getting the result as  [Record: source = " sourceFromJson ", resource = "resourceFromJson" ] but
 I want the result to be  [Record: source = "sourceFromObject", resource = "resourceFromJson" ]

Could anyone please help on this.

Regards,
Senthil



Tatu Saloranta

unread,
Dec 14, 2022, 8:57:27 PM12/14/22
to jackso...@googlegroups.com
That cannot be done with Records in general: Records are immutable so
`readerForUpdating()` won't be able to use setters (although might try
to force changes via fields).

Otherwise I would suggest overriding `setSource(...)` and other
methods to implement logic you want: you could assign only if there is
no non-null value.
But that won't really work with Records: a new instance will be
created from just the data passed.

-+ Tatu +-

Tatu Saloranta

unread,
Jan 22, 2023, 6:50:56 PM1/22/23
to jackso...@googlegroups.com
There is no out of the box functionality for this, although it would
theoretically be doable with custom deserializer.

However, I suspect that it'd be easier to implement by reader json as
`JsonNode`, serializing record as JsonNode,
and modifying former with latter (leaving only properties for which
there are no non-null values), and then deserializing as record.

-+ Tatu +-

>
> Regards,
> Senthil
>
>
>
> --
> You received this message because you are subscribed to the Google Groups "jackson-user" group.
> To unsubscribe from this group and stop receiving emails from it, send an email to jackson-user...@googlegroups.com.
> To view this discussion on the web visit https://groups.google.com/d/msgid/jackson-user/a7cc274e-bab2-405a-bbcb-4afdfc011e29n%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages