I encountered the problem when I try to answer the question:
Request with multipart/form-data returns 415 error
According to the document about HttpMessageConverters
(Spring Boot Features 7.1.2. HttpMessageConverters), we can add a custom HttpMessageConverter
by configuring a bean of HttpMessageConverters
. I see a JSON response that I don't expected when I configure a custom converter.
I created a simple end point that returns a JSON consists of Date
and LocalDate
fields.
- When I don't configure any custom converter, I get them in
String
format.
{
"date": "2020-02-29T06:13:45.875+0000",
"localDate": "2020-02-29"
}
- When I configure a custom converter which does NOT handle JSON responses, I get them in
Number
format.
{
"date": 1582956902270,
"localDate": [
2020,
2,
29
]
}
My questions are:
- Why is the format of the JSON response changed even when I configure a custom converter never handling JSON responses?
- How to avoid it? I want to make Spring Boot handle JSON responses in the same way that it does when I don't configure custom converters.
[Sample Application]
Spring Boot Version: 2.2.5.RELEASE
@RestController
@SpringBootApplication
public class MyApplication {
@GetMapping("/test")
public SomeDates test() {
return new SomeDates(new Date(), LocalDate.now());
}
@Data
public class SomeDates {
private final Date date;
private final LocalDate localDate;
}
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
@Configuration
public class MyConfigurer {
@Bean
public HttpMessageConverters customConverters() {
return new HttpMessageConverters(new ConverterDoingNothingForTestPurpose());
}
public static class ConverterDoingNothingForTestPurpose implements HttpMessageConverter<Object> {
@Override
public boolean canRead(Class<?> clazz, MediaType mediaType) {
return false;
}
@Override
public boolean canWrite(Class<?> clazz, MediaType mediaType) {
return false;
}
@Override
public List<MediaType> getSupportedMediaTypes() {
return Collections.emptyList();
}
@Override
public Object read(Class<?> clazz, HttpInputMessage inputMessage)
throws IOException, HttpMessageNotReadableException {
throw new RuntimeException("This converter should not be invoked.");
}
@Override
public void write(Object t, MediaType contentType, HttpOutputMessage outputMessage)
throws IOException, HttpMessageNotWritableException {
throw new RuntimeException("This converter should not be invoked.");
}
}
}