简体   繁体   中英

What is the proper way to initialize Jersey client with a module?

So, this should not be this hard. I'm trying to have an ObjectMapper in a Jersey client application deserialize a java.time.LocalDateTime . Sadly, this results in the exception:

 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?)

Okay, so there's a module that implements the proper serializers/deserializers for the Java time types: com.fasterxml.jackson.datatype.jsr310.JavaTimeModule . Great, so we just need to install that module in the application, and all is well. But, how?

The documentation is sort of silent on this. I've tried every sensible combination of the following lines of init code, with no luck:

    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. 

The ObjectMapper above is a separate one that was laying around in my application anyone (for use outside of the client), and is initialized with:

    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());

It also can't map LocalDateTime.

So, what is the proper way to configure a Jersey client to use that module and deserialize java.time.LocalDateTime ??

Try val mapper = ObjectMapper() mapper.registerModule(JavaTimeModule())

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

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

(Apologies for the kotlin - translates to Java as you'd expect).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM