I want to get the dates in a format of dd/MM/yyyy
so,I wrote this code first:
@GetMapping("/testAjax.json")
public ResponseBody<?> AjaxResponse testAjax(){
AjaxResponse response = new AjaxResponse();
DateTimeTest test = new DateTimeTest();
test.setDateTime(LocalDateTime.now());
response.addResponse("date", LocalDateTime.now());
response.addResponse("test", test);
return response;
}`
and I got this response:
{"status":false,"response":{"date":[2024,10,21,11,12,20,417960408],"test":{"dateTime":[2024,10,21,11,12,20,417940363]}}}
Tried by adding
@Bean
public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter();
ObjectMapper mapper = new ObjectMapper();
JavaTimeModule module = new JavaTimeModule();
mapper.registerModule(module);
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
module.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(formatter));
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
jsonConverter.setObjectMapper(mapper);
return jsonConverter;
}
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(mappingJackson2HttpMessageConverter());
}
But not working,
2
Answers
maybe this code solve your problem:
I remember encountering this issue before especially when i comes to timestamps and date types in Restful api response … ,The best thing you can do is to serialize your attributes of date and time by JsonFormat in your entity:
creating a Date class mapper is no longer required in Spring Boot since the auto-configuration manager that automatically but in you really need to serialize and deserialize Localedate manually try this :