无法使用Jackson解组LocalDate和LocalTime类

问题描述 投票:1回答:1

我正在使用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));
                            });
                        })),
java json akka unmarshalling akka-http
1个回答
0
投票

杰克逊需要额外的module用于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提取为“全局”变量。

© www.soinside.com 2019 - 2024. All rights reserved.