I'm using springBoot to develop a REST APi. And i have a LocalDate field "firstDate" in the response model of a GET endpoint. But this LocalDate is serializable as an array in the response's json!
"firstDate": [
2021,
3,
1
],
So for consuming this APi, i have to define this date in my DTO as an array! which is not good! My reponse models of th API are generated with swagger so i can not use @JsonFormat(pattern="yyyy-MM-dd")
Can you help me please and tell me how to serialize LocalDate properly in this case ?
Thank you very much.
My dates defined as LocalDateTime were been serializaded as an array like this:
"timestamp": [
2023,
2,
15,
10,
30,
45,
732425200
],
So here is what I did in my WebConfig.java:
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
// other configs
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
WebMvcConfigurer.super.extendMessageConverters(converters);
converters.add(new MappingJackson2HttpMessageConverter(
new Jackson2ObjectMapperBuilder()
.dateFormat(new StdDateFormat())
.featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.build()));
}
}
Now everything is good again:
"timestamp": "2023-02-15T10:32:06.5170689",
Hope it's been helpful. Some topics that helped me achieve that:
Configure LocaldateTime in Spring Rest API
How to customise the Jackson JSON mapper implicitly used by Spring Boot?
Can't serialize java.time.LocalDate as a String with Jackson
I think this WebConfig.class is unnecessary. You could try something like that in your field firstDate:
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd")
private LocalDate firstDate;
There's no make sense define the field as an array in DTO because of the swagger config
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With