Is Default serialization format of Date has changed with recent Spring boot versions/Jackson Versions?
It comes from jackson-databind 2.11.0.(diff)
- Spring Boot 2.2.0: 2.10.0
- Spring Boot 2.2.8: 2.10.4
- Spring Boot 2.3.0: 2.11.0
so, it seems this behavior is Spring Boot 2.3.0 or later.
Spring Boot Jackson does not serialize timestamps in Long
Spring's Jackson converts types by default. In order to change type, conversions need to override the default configuration. The question above can be fixed by the following configuration.
@Bean
public JavaTimeModule javaTimeModule() {
var javaTimeModule = new JavaTimeModule();
javaTimeModule.addSerializer(Instant.class, new InstantToLongSerializer());
return javaTimeModule;
}
static class InstantToLongSerializer extends JsonSerializer<Instant> {
@Override
public void serialize(Instant value, JsonGenerator gen, SerializerProvider serializers)
throws IOException {
gen.writeNumber(value.toEpochMilli());
}
}
Jackson change timestamp format
I want to change the
java.sql.Timestamp
format globally.
Set a date format to your ObjectMapper
instance:
ObjectMapper mapper = new ObjectMapper();
mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S"));
In Spring applications, you can expose the ObjectMapper
instance as a bean:
@Bean
public ObjectMapper objectMapper() {
ObjectMapper mapper = new ObjectMapper();
mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S"));
return mapper;
}
In Spring Boot you can use the property spring.jackson.date-format
to define the date format:
spring.jackson.date-format: yyyy-MM-dd HH:mm:ss.S
For more details on the common application properties, refer to the documentation.
Consider the following code:
Map<String, Object> data = new HashMap<>();
data.put("date", new Timestamp(ZonedDateTime.now().toInstant().toEpochMilli()));
System.out.println(mapper.writeValueAsString(data));
It will print:
{"date":"2018-04-26 07:25:14.408"}
Related Topics
What Are the Main Uses of Yield(), and How Does It Differ from Join() and Interrupt()
Differencebetween an Ordered and a Sorted Collection
Create MySQL Database from Java
Comparing and Thencomparing Gives Compile Error
Multiple Clients Access the Server Concurrently
What Does the Colon (:) Operator Do
Spring Data: Override Save Method
Cannot Create Jdbc Driver of Class ' ' for Connect Url 'Null':I Do Not Understand This Exception
What Is the "Default" Implementation of Method Defined in an Interface
Generate Java Classes from .Xsd Files...
How to Serialize a List in Java
What Determines Kafka Consumer Offset