使用对象映射器返回JSON,由我选择

时间:2015-10-23 17:18:44

标签: java json spring spring-mvc jackson

我有自定义ObjectMapper,其配置方式如下:

@Configuration
@EnableWebMvc
@ComponentScan({"xxx.service", "xxx.controller" })
public class SpringWebConfig extends WebMvcConfigurerAdapter {

........

    @Bean
    public MappingJackson2HttpMessageConverter httpMessageConverter() {
        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        converter.setObjectMapper(jacksonMapper());
        return converter;
    }

    @Bean
    @Scope(value = "singleton", proxyMode = ScopedProxyMode.TARGET_CLASS)
    public MyOwnMapper jacksonMapper(){
        return new MyOwnMapper();
    }

}

据我所知,@ResponseBody自动使用默认ObjectMapper。在我的情况下,默认ObjectMapperMyOwnMapper。但是我要做的是,如果在@ResponseBody的某种方法中,我想使用其他ObjectMapper(例如,来自ObjectMapper包的标准com.fasterxml.jackson.databind)?我尝试过像

这样的东西
@RequestMapping("/card")
    @ResponseBody
    public Map card(@RequestParam int id) throws JsonProcessingException {
        ObjectMapper mapper=new ObjectMapper(); 
        return mapper.writeValueAsString(cardService.getCommonInfo(id));
    }

然后我的方法返回简单的字符串,而不是JSON。

0 个答案:

没有答案