Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a custom Jackson ObjectMapper for Jersey 1.0 client

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?

like image 725
woezelmann Avatar asked Jul 08 '15 13:07

woezelmann


People also ask

Does Jersey use Jackson?

Jersey uses Jackson internally to convert Java objects to JSON and vice versa.

What is ObjectMapper class in Jackson?

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.

Can I reuse ObjectMapper?

Therefore it is recommended that you reuse your ObjectMapper instance. The Jackon ObjectMapper is thread-safe so it can safely be reused.

Can ObjectMapper be shared?

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.


1 Answers

To configure the ObjectMapper for use with Jersey, you could

  1. 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);
    
  2. 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.

like image 161
Paul Samsotha Avatar answered Sep 25 '22 16:09

Paul Samsotha