Returning JsonObject using @ResponseBody in SpringMVC

后端 未结 2 1317
鱼传尺愫
鱼传尺愫 2020-11-28 10:57

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

2条回答
  •  盖世英雄少女心
    2020-11-28 11:21

    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);
    }
    }
    

提交回复
热议问题