如何为Jersey 1.0客户端设置自定义Jackson Jackson ObjectMapper

woe*_*ann 4 java json jersey jackson jersey-1.0

我正在使用Jersey 1.0 http-client调用资源并反序列化响应JSON,如下所示:

Client client = Client.create(new DefaultClientConfig())
ClientResponse clientResponse = client.resource("http://some-uri").get(ClientResponse.class)
MyJsonRepresentingPOJO pojo = clientResponse.getEntity(MyJsonRepresentingPOJO.class)
Run Code Online (Sandbox Code Playgroud)

现在,响应JSON具有一些新字段,并且出现以下异常:

com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "xyz"
Run Code Online (Sandbox Code Playgroud)

如何将杰克逊的反序列化模式更改为NON-STRICT,以便它将忽略新字段?

Pau*_*tha 6

要配置ObjectMapper以与Jersey一起使用,您可以

  1. 创建ContextResolver所看到这里,并注册与客户端的解析。

    ClientConfig config = new DefaultClientConfig();
    config.register(new ObjectMapperContextResolver());
    Client client = Client.create(config);
    
    Run Code Online (Sandbox Code Playgroud)
  2. 或实例化JacksonJsonProvider传入ObjectMapper的构造函数参数。然后向Client

    ClientConfig config = new DefaultClientConfig();
    config.register(new JacksonJsonProvider(mapper));
    Client client = Client.create(config);
    
    Run Code Online (Sandbox Code Playgroud)

    请注意,如果您使用的是JAXB批注,则需要使用 JacksonJaxbJsonProvider

要忽略未知属性,可以在上设置配置属性ObjectMapper,如Sam B链接所示。即

mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
Run Code Online (Sandbox Code Playgroud)

编辑

我在上面的示例中犯了一个错误。这里没有register的方法,ClientConfig在泽西岛1.x中 而是使用getSingletons().add(...)。有关更多信息,请参见API