如何从 JAX-RS 客户端中提取 ObjectMapper? [英] How to extract ObjectMapper from JAX-RS Client?
问题描述
我正在使用 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!