I am using Jersey 1.0 http-client to call a resource and deserialize the response JSON like this:
Client client = Client.create(new DefaultClientConfig())
ClientResponse clientResponse = client.resource("http://some-uri").get(ClientResponse.class)
MyJsonRepresentingPOJO pojo = clientResponse.getEntity(MyJsonRepresentingPOJO.class)
Now the response JSON has some new fields and I am getting following exception:
com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "xyz"
How can I change jackson's deserialization-mode to NON-STRICT, so that it will ignore the new fields?
Jersey uses Jackson internally to convert Java objects to JSON and vice versa.
ObjectMapper is the main actor class of Jackson library. ObjectMapper class ObjectMapper provides functionality for reading and writing JSON, either to and from basic POJOs (Plain Old Java Objects), or to and from a general-purpose JSON Tree Model (JsonNode), as well as related functionality for performing conversions.
Therefore it is recommended that you reuse your ObjectMapper instance. The Jackon ObjectMapper is thread-safe so it can safely be reused.
ObjectMapper is thread safe, so it does not have to be created for each request that needs serialization/deserialization. It is recommended to declare a static ObjectMapper instance that should be shared as much as possible.
To configure the ObjectMapper
for use with Jersey, you could
Create a ContextResolver
as seen here, and register the resolver with the client.
ClientConfig config = new DefaultClientConfig();
config.register(new ObjectMapperContextResolver());
Client client = Client.create(config);
OR Instantiate the JacksonJsonProvider
passing in the ObjectMapper
as a constructor argument. Then register the provider with the Client
ClientConfig config = new DefaultClientConfig();
config.register(new JacksonJsonProvider(mapper));
Client client = Client.create(config);
Note, if you are using JAXB annotations, you'll want to use the JacksonJaxbJsonProvider
To ignore the unknown properties, you can you set a configuration property on the ObjectMapper
, as shown in the link from Sam B.. i.e
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
EDIT
I made a mistake in the examples above. There is no register
method for the ClientConfig
in Jersey 1.x. Instead, use getSingletons().add(...)
. See the API for more info.
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