• Home
  • How to serialize an instant without nanoseconds using spring boot with jackson?

How to serialize an instant without nanoseconds using spring boot with jackson?

To serialize an Instant object without nanoseconds using Spring Boot with Jackson, you can use the following steps:

  1. Configure the ObjectMapper bean to use the JavaTimeModule:
@Bean
public ObjectMapper objectMapper() {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(new JavaTimeModule());
return objectMapper;
}
  1. Use the @JsonFormat annotation to specify the format of the Instant object:
public class MyDto {
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss'Z'", timezone = "UTC")
private Instant date;

// Getters and setters for date
}
  1. When serializing the Instant object, it will now be formatted as a string in the specified pattern, without the nanoseconds.
MyDto dto = new MyDto();
dto.setDate(Instant.now());

String json = objectMapper.writeValueAsString(dto);

This will produce a JSON string like the following:

{"date":"2022-12-23T00:00:00Z"}

Note that the JavaTimeModule also provides additional customization options for serializing and deserializing other Java 8 date and time types, such as LocalDate, LocalTime, etc. You can read more about these options in the Jackson documentation.