jackson 在Spring Boot中写入日期作为时间戳

yc0p9oo0  于 2022-11-09  发布在  Spring
关注(0)|答案(1)|浏览(100)

我有一个Spring Boot应用程序,在其中我使用FasterXML Jackson库进行JSON转换,但默认情况下,日期被序列化为时间戳,这正是我想要的。

MyObj obj = new MyObj();
Date dateUnderTest = new Date();
obj.setLastUpdatedAt(dateUnderTest);
String objStr = objectMapper.writeValueAsString(obj);
JsonNode jsonNode = objectMapper.readTree(objStr);
String readUpdatedAt = jsonNode.findValue("updated_at").asText();
Assert.assertEquals(Long.parseLong(readUpdatedAt), dateUnderTest.getTime());

这个测试是成功的。但是,当我尝试写 obj 作为我的REST API响应时,我看到的日期格式为:

"updated_at": "2021-04-19T23:33:06.065+0000",

我认为Spring Boot正在使用其他序列化库进行转换。我需要一个长时间戳。我如何更改该转换?

emeijp43

emeijp431#

Spring的Jackson转换器有自己的序列化器。要设置它,我们可以在 application.propertiesapplication.yml 文件中添加以下配置:

spring.jackson.serialization.write_dates_as_timestamps: true

相关问题