I am using the new Java API (JSR 353) for JSON in a SpringMVC project.
The idea is to generate some piece of Json data and have it returned to the client. The contro
The answer from Sotirios Delimanolis does indeed work, but in my case I had to ensure the proper HttpMessageConverter order was in place. This is because I needed to also convert JodaTime values to ISO 8601 format. This custom WebMvcConfigurerAdapter Configuration worked for me:
@Configuration
public class WebConfiguration extends WebMvcConfigurerAdapter {
@SuppressWarnings("UnusedDeclaration")
private static final Logger log = LoggerFactory.getLogger(WebConfiguration.class);
public void configureMessageConverters(List> converters) {
log.info("Configuring jackson ObjectMapper");
final MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
final ObjectMapper objectMapper = new ObjectMapper();
//configure Joda serialization
objectMapper.registerModule(new JodaModule());
objectMapper.configure(com.fasterxml.jackson.databind.SerializationFeature.
WRITE_DATES_AS_TIMESTAMPS, false);
// Other options such as how to deal with nulls or identing...
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
converter.setObjectMapper(objectMapper);
StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter();
/*
StringHttpMessageConverter must appear first in the list so that Spring has a chance to use
it for Spring RestController methods that return simple String. Otherwise, it will use
MappingJackson2HttpMessageConverter and clutter the response with escaped quotes and such
*/
converters.add(stringHttpMessageConverter);
converters.add(converter);
super.configureMessageConverters(converters);
}
}