[英]Unable to unmarshal LocalDate and LocalTime class using Jackson
我正在使用akka进行POST路由,在这里我将Json数据反序列化为Video对象,但是以下curl请求:
curl -H "Content-Type: application/json" -X POST -d '{"title": "Video Title","videoDate":"10-2-2018","videoTime":"12:10:11"}' http://localhost:9090/updatedData
给出错误: Cannot unmarshal JSON as Video
当我从json删除videoDate和videoTime字段时,请求工作正常。
Jackson.unmarshaller(VideoInfo.class)
//Video.class
public class Video {
private String title;
private LocalDate videoDate;
private LocalTime videoTime;
}
使用的Maven依赖是
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.8</version>
</dependency>
这是我的路线/ updatedData
post(() ->
path("updatedData", () -> {
LOGGER.info("calling POST /updatedData");
return entity(Jackson.unmarshaller(Video.class), videoInfo -> {
LOGGER.debug("Payload received : " + videoInfo.toString());
ArrayList<HttpHeader> headers = getCORSHeaders();
return respondWithHeaders(headers, () ->
onSuccess(videoFrameProcessing.updateVideoInfo(videoInfo), this::complete));
});
})),
Jackson需要Java 8 Time
API的附加模块 。
模块
jackson-datatype-jsr310
已弃用 ,现在属于
jackson-modules-java8
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>2.9.8</version>
</dependency>
这意味着您需要手动注册该模块
final ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(new JavaTimeModule());
Akka Jackson
类提供unmarshaller
的重载版本,您可以使用它传递自定义版本的ObjectMapper
public static <T> Unmarshaller<HttpEntity, T> unmarshaller(ObjectMapper mapper, Class<T> expectedType) {
return Unmarshaller.forMediaType(MediaTypes.APPLICATION_JSON, Unmarshaller.entityToString())
.thenApply(s -> fromJSON(mapper, s, expectedType));
}
所以,代替
Jackson.unmarshaller(Video.class)
采用
Jackson.unmarshaller(objectMapper, Video.class);
objectMapper
参数是自定义ObjectMapper
final ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(new JavaTimeModule());
完整的代码段是
post(() ->
path("updatedData", () -> {
LOGGER.info("calling POST /updatedData");
final ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(new JavaTimeModule());
return entity(Jackson.unmarshaller(objectMapper, Video.class), videoInfo -> {
LOGGER.debug("Payload received : " + videoInfo.toString());
ArrayList<HttpHeader> headers = getCORSHeaders();
return respondWithHeaders(headers, () ->
onSuccess(videoFrameProcessing.updateVideoInfo(videoInfo), this::complete));
});
})),
显然,将ObjectMapper
提取为“全局”变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.