Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling Unknown JSON Properties with Jackson

Tags:

json

jackson

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?

like image 692
henrik_lundgren Avatar asked May 04 '10 08:05

henrik_lundgren


People also ask

Does Jackson ignore unknown properties?

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.

How do I ignore properties in Jackson?

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.

How do I ignore unrecognized fields Jackson?

You can ignore the unrecognized fields by configuring the ObjectMapper class: mapper. configure(DeserializationFeature. FAIL_ON_UNKNOWN_PROPERTIES, false);

How do I ignore properties in ObjectMapper?

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.


1 Answers

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.

like image 149
skaffman Avatar answered Sep 18 '22 00:09

skaffman