'Write a date as a timestamp in Spring Boot
I have a Spring Boot application where I am using the FasterXML Jackson library for my JSON conversions. But by default, the date is serialized as a timestamp and that is what I want.
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());
That test is successful. However, when I try to write obj as my REST API response, I see the date format as:
"updated_at": "2021-04-19T23:33:06.065+0000",
I think Spring Boot is using some other serialization library for this conversion. I want a long timestamp. How can I change that conversion?
Solution 1:[1]
Spring's Jackson converter has its own serializer. To set it, we can add this configuration in our application.properties or application.yml file:
spring.jackson.serialization.write_dates_as_timestamps: true
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Peter Mortensen |
