JAX-RS(新泽西州)和杰克逊无法正确序列化LocalDate

时间:2018-07-11 19:17:36

标签: java spring-boot jackson jersey-2.0 jersey-client

我们最近升级到了Spring Boot 2.0,并因此升级了2.1的JAX-RS和2.26的Jackson。

现在的问题是,我尝试通过POST(序列化和)发送的Java对象具有类型java.time.LocalDate的字段,并且没有正确地序列化(成JSON)。这是更新后的结果:

...
"birthDate": {
  "year": 1991,
  "month": "JANUARY",
  "chronology": {
    "id": "ISO",
    "calendarType": "iso8601"
  },
  "monthValue": 1,
  "dayOfMonth": 1,
  "dayOfWeek": "TUESDAY",
  "era": "CE",
  "dayOfYear": 1,
  "leapYear": false
},
...

...相反,birthDate应该像以前"birthDate": "1991-01-01"一样发送。

客户端配置为:

final ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
final JacksonJsonProvider provider = new JacksonJsonProvider();
provider.setMapper(mapper);
return ClientBuilder.newClient(new ClientConfig(provider))
    .target("http://hostname/api/some-path")
    .path("");

我还尝试注释了birthDate提交的@JsonFormat(pattern = "yyyy-MM-dd")

1 个答案:

答案 0 :(得分:1)

就我而言,升级后有效的是:

  • 删除com.fasterxml.jackson.jaxrs:jackson-jaxrs-json-provider依赖项
  • 添加org.glassfish.jersey.media:jersey-media-json-jackson依赖项
  • 修复所有:troll_face:出现的编译问题
  • 使用JacksonJaxbJsonProvider代替JacksonJsonProvider-这对我来说完全是意外的

最后,客户端的最终配置如下所示:

final ObjectMapper mapper = new ObjectMapper()
    .registerModule(new JavaTimeModule())
    .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
return ClientBuilder.newClient() // ClientConfig if needed
    .register(new JacksonJaxbJsonProvider(mapper, JacksonJaxbJsonProvider.DEFAULT_ANNOTATIONS))
    .target("http://hostname/api/some-path")
    .path("");