2017-06-13 116 views
1

所以,這不應該這麼難。我試圖在Jersey客戶端應用程序中使用ObjectMapper反序列化java.time.LocalDateTime。可悲的是,這導致例外:用模塊初始化Jersey客戶端的正確方法是什麼?

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的正確方法是什麼?

回答

0

嘗試 VAL映射器= ObjectMapper() mapper.registerModule(JavaTimeModule())

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

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

(很抱歉沒能科特林 - 轉換爲Java如你所期望的那樣)。

相關問題