javajsonjerseyjacksonjersey-1.0

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?


Solution

  • 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.