如何从 JAX-RS 客户端中提取 ObjectMapper?客户端、JAX、RS、ObjectMapper

由网友(曾经薄荷少年凉。)分享简介:我正在使用 Jersey JAX-RS 客户端(2.0 版).我知道它使用 Jackson ObjectMapper 来生成和解析 JSON.我想使用同一个对象为一些 java 类生成 JSON,以便我可以将它们写入日志.I am using Jersey JAX-RS client (version 2.0). I...

我正在使用 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_PROPERTIESFAIL_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.

阅读全文

相关推荐

最新文章