问题描述
我使用的是 Jersey JAX-RS 客户端(2.0 版).我知道它使用 Jackson ObjectMapper 来生成和解析 JSON.我想使用相同的对象为某些 Java 类生成 JSON,以便我可以将它们写入日志.
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.
我知道我可以创建一个 ObjectMapper 的新实例,但我更喜欢请求 Jersey Client 给我一个它正在使用的实例的引用.我怎样才能做到这一点?Jersey 2.0 知道 Jackson,因为它首先包含一个 JacksonFeature 类,用于配置 Jackson 功能.
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.
推荐答案
我通过添加以下静态成员解决了这个问题:
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);
请注意,第二个声明不仅仅用于配置FAIL_ON_UNKNOWN_PROPERTIES
或FAIL_ON_EMPTY_BEANS
;我出于其他一些原因使用 object_mapper
.
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.
这篇关于如何从 JAX-RS 客户端提取 ObjectMapper?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!