For deserializing json with unknown field into an object there's @JsonAnySetter.
But what if I read such json into my object, modify some known fields and write it back to json? The unknown properties will be lost.
How do I handle such cases? Is it possible to map an object or do I have to read the data into a JsonNode or Map?
There are two ways to ignore Unknown fields are provided by Jackson API. Both approaches will be discussed here and we will also see how to use them and when to use @JsonIgnoreProperties and when to ignore unknown fields in JSON globally at the ObjectMapper level.
Ignore All Fields by Type Finally, we can ignore all fields of a specified type, using the @JsonIgnoreType annotation. If we control the type, then we can annotate the class directly: @JsonIgnoreType public class SomeType { ... } More often than not, however, we don't have control of the class itself.
You can ignore the unrecognized fields by configuring the ObjectMapper class: mapper. configure(DeserializationFeature. FAIL_ON_UNKNOWN_PROPERTIES, false);
ObjectMapper; ObjectMapper objectMapper = new ObjectMapper(); objectMapper. configure(DeserializationFeature. FAIL_ON_UNKNOWN_PROPERTIES, false); This will now ignore unknown properties for any JSON it's going to parse, You should only use this option if you can't annotate a class with @JsonIgnoreProperties annotation.
Unmarshalling into a custom java class has its advantages and disadvantages. It's gives you nice static typing, but it's well, static. The javadoc for @JsonAnySetter
suggests that it's similar to JAXB's @XmlAnyElement
, but unlike @XmlAnyElement
, the data objects don't contain naming information, so it's a one-way street.
if you need to handle dynamic JSON streams, then you need to bite the bullet and use Map
or JsonNode
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With