使用模块初始化Jersey客户端的正确方法是什么?

时间:2017-06-13 23:28:14

标签: java module jersey-client

所以,这不应该是这么难。我正在尝试在Jersey客户端应用程序中使用ObjectMapper反序列化java.time.LocalDateTime。可悲的是,这导致例外:

 Exception in thread "main" javax.ws.rs.client.ResponseProcessingException: com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of java.time.LocalDateTime: no suitable constructor found, can not deserialize from Object value (missing default constructor or creator, or perhaps need to add/enable type information?)

好的,所以有一个模块为Java时间类型实现了正确的序列化器/反序列化器:com.fasterxml.jackson.datatype.jsr310.JavaTimeModule。太棒了,所以我们只需要在应用程序中安装该模块,一切都很顺利。但是,怎么样?

文档对此有点沉默。我已经尝试了以下几行初始代码的合理组合,但没有运气:

    ClientBuilder builder = ClientBuilder.newBuilder();
    builder.register(new RequestFilter(this));
    builder.register(new ResponseFilter(this));

    builder.register(new JacksonJsonProvider(objectMapper));
    builder.register(new JavaTimeModule());

    ClientConfig cc = new ClientConfig();
    cc.register(new JacksonJsonProvider(objectMapper));
    cc.register(new JavaTimeModule());
    // cc.getClasses().add(JavaTimeModule.class);  // no go, this collection is unmodifiable

    builder.register(cc);

    // Client client = builder.build();
    Client client = builder.withConfig(cc).build();

    client.register(new JacksonJsonProvider(objectMapper));
    client.register(new JavaTimeModule());
    //client.getConfiguration().getClasses().add(JavaTimeModule.class); // and this one too. 

上面的ObjectMapper是一个独立的应用程序(在客户端之外使用),并且初始化为:

    objectMapper = new ObjectMapper();
    objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
    objectMapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
    objectMapper.registerModule(new JavaTimeModule());

它也无法映射LocalDateTime。

那么,配置Jersey客户端使用该模块并反序列化java.time.LocalDateTime的正确方法是什么?

1 个答案:

答案 0 :(得分:0)

尝试     val mapper = ObjectMapper()     mapper.registerModule(JavaTimeModule())

val provider = JacksonJaxbJsonProvider()
provider.setMapper(mapper)

val clientConfig = ClientConfig()
clientConfig.register(provider)

(对kotlin表示歉意 - 按照您的预期转换为Java。)