Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract ObjectMapper from JAX-RS Client?

I am using Jersey JAX-RS client (version 2.0). I know it is using a Jackson ObjectMapper to generate and parse JSON. I want to use that same object to generate JSON for some java classes so that I can write them to a log.

I know I can create a new instance of ObjectMapper but I prefer to request Jersey Client to give me a reference to the one it is using. How can I do this? Jersey 2.0 is aware of Jackson because it includes a JacksonFeature class that is used to configure the Jackson feature in the first place.

like image 701
necromancer Avatar asked May 04 '13 23:05

necromancer


People also ask

Is Fasterxml ObjectMapper thread-safe?

Mapper instances are fully thread-safe provided that ALL configuration of the instance occurs before ANY read or write calls.

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 ObjectMapper be reused?

ObjectMapper class can be reused and we can initialize it once as Singleton object. There are so many overloaded versions of readValue() and writeValue() methods to work with byte array, File, input/output stream and Reader/Writer objects.

What is the use of ObjectMapper readValue?

The simple readValue API of the ObjectMapper is a good entry point. We can use it to parse or deserialize JSON content into a Java object. Also, on the writing side, we can use the writeValue API to serialize any Java object as JSON output.


1 Answers

I solved this by adding the following static members:

private static JacksonJsonProvider jackson_json_provider = new JacksonJaxbJsonProvider()
      .configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false)
      .configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false);

private static ObjectMapper object_mapper = jackson_json_provider.locateMapper(
      Object.class, MediaType.APPLICATION_JSON_TYPE);

private static Client client = ClientBuilder.newClient().register(jackson_json_provider);

Note that the second declaration is not needed just to configure FAIL_ON_UNKNOWN_PROPERTIES or FAIL_ON_EMPTY_BEANS; I use object_mapper for some other reasons.

like image 183
necromancer Avatar answered Oct 21 '22 18:10

necromancer