edw*_*ise 6 java rest jersey jackson jsr310
我正在使用 jersey 客户端进行一些 PoC 来使用 REST 服务,但我在使用 LocalDateTime 格式的字段时遇到了问题。REST 服务响应如下:
{
"id": 12,
"infoText": "Info 1234",
"creationDateTime": "2001-12-12T13:40:30"
}
Run Code Online (Sandbox Code Playgroud)
和我的实体类:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
我的 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>
Run Code Online (Sandbox Code Playgroud)
我的代码使用 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));
Run Code Online (Sandbox Code Playgroud)
我遇到了这样的异常:
...
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"])
...
Run Code Online (Sandbox Code Playgroud)
我缺少什么?我用 RestTemplate (Spring Rest 客户端)尝试过,无需任何配置即可完美运行。
jsr310模块仍然需要向Jackson注册。您可以在 a 中执行此操作,ContextResolver如下所示,您可以在其中Jsr310Module注册ObjectMapper
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JSR310Module());
Run Code Online (Sandbox Code Playgroud)
然后您ContextResolver向客户端注册。将会发生的情况是,JacksonJsonProvider应该调用该getContext方法,并检索ObjectMapper用于(反)序列化的。
ContextResolver您也可以在服务器端使用相同的方法。如果您只需要在客户端上使用此功能,另一种方法是JacksonJsonProvider使用ObjectMapper. 稍微简单一点
new JacksonJsonProvider(mapper)
Run Code Online (Sandbox Code Playgroud)