我正在使用jersey来使用REST服务来执行一个小的PoC,而且我在LocalDateTime格式的字段中遇到了问题。REST服务响应如下:
{
"id": 12,
"infoText": "Info 1234",
"creationDateTime": "2001-12-12T13:40:30"
}我的实体类:
package com.my.poc.jerseyclient;
import java.time.LocalDateTime;
public class Info {
private Long id;
private String infoText;
private LocalDateTime creationDateTime;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getInfoText() {
return infoText;
}
public void setInfoText(String infoText) {
this.infoText = infoText;
}
public LocalDateTime getCreationDateTime() {
return creationDateTime;
}
public void setCreationDateTime(LocalDateTime creationDateTime) {
this.creationDateTime = creationDateTime;
}
}Pom.xml中的依赖项:
<dependencies>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>2.21</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-json-provider</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>2.6.1</version>
</dependency>
</dependencies>我的代码与jersey客户端一起编写了GET /api/info/123:
Client client = ClientBuilder.newClient(new ClientConfig().register(JacksonJsonProvider.class);
WebTarget webTarget = client.target("http://localhost:8080/api/").path("info/");
Response response = webTarget.path("123").request(MediaType.APPLICATION_JSON_TYPE).get();
System.out.println("GET Body (object): " + response.readEntity(Info.class));我得到了这样的例外:
...
Caused by: com.fasterxml.jackson.databind.JsonMappingException: Can not instantiate value of type [simple type, class java.time.LocalDateTime] from String value ('2001-12-12T13:40:30'); no single-String constructor/factory method
at [Source: org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$UnCloseableInputStream@21b2e768; line: 1, column: 32] (through reference chain: com.my.poc.jerseyclient.Info["creationDateTime"])
...我遗漏了什么?我在RestTemplate (Spring客户端)中尝试了这一点,它在没有任何配置的情况下工作得很好。
发布于 2015-09-08 07:27:11
jsr310模块仍然需要向杰克逊注册。您可以在ContextResolver中作为seen here注册Jsr310Module,在ObjectMapper中注册Jsr310Module。
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JSR310Module());然后将ContextResolver注册到客户端。将发生的情况是,JacksonJsonProvider应该调用getContext方法,并检索用于(反)序列化的ObjectMapper。
您还可以在服务器端使用相同的ContextResolver。如果您只需要在客户机上使用此功能,则另一种方法是使用JacksonJsonProvider简单地构造ObjectMapper。稍微简单一点
new JacksonJsonProvider(mapper)发布于 2019-03-27 19:47:49
为了客户端的功能,将所有内容组合在一起:
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JSR310Module());
JacksonJsonProvider provider = new JacksonJsonProvider(mapper);
Client client = ClientBuilder.newClient(new ClientConfig().register(provider));https://stackoverflow.com/questions/32451355
复制相似问题