For a Spring MVC (not Spring Boot) I've had to change the configuration class that extended WebMvcConfigurationSupport to implement WebMvcConfigurer and add the @EnableWebMvc annotation. This causes problems with the conversion of the responses for several endpoints. The project defaults to application/json and it is used for most of the responses however, there are several endpoints which return application/xml and even a few that return text/plain. JSON responses are modified to remove fields containing null using the following Java config:
@Bean
public MappingJackson2HttpMessageConverter jsonConverter() {
List<MediaType> supportedMediaTypes = new ArrayList<>();
supportedMediaTypes.add(MediaType.APPLICATION_JSON);
Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
builder.serializationInclusion(JsonInclude.Include.NON_NULL);
builder.timeZone(TimeZone.getTimeZone(timeZone));
MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter(
builder.build()
);
jsonConverter.setSupportedMediaTypes(supportedMediaTypes);
return jsonConverter;
}
This causes JSON responses to be returned correctly but results in an exception for the text/plain endpoints. They then produce an error:
No converter for [class java.lang.String] with preset Content-Type 'null'
The error can be resolved by adding the default string converter before the JSON converter:
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(new StringHttpMessageConverter());
converters.add(jsonConverter());
}
However, this causes a problem specifically for endpoints that return JSON but in Java only have String as the return type. A string in between double quotes should be returned: "response", but they only return the string without quotes: response. This makes most clients to not recognise the response as valid JSON. Curiously POJOs are still converted to valid JSON.
How can I configure my Spring MVC (not Spring Boot) project using a configuration class that implements WebMvcConfigurer and is annotated with @EnableWebMvc to return JSON without null fields and single strings as valid JSON (e.g. with double quotes: "response") but also plain text?