我有自定义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
。在我的情况下,默认ObjectMapper
为MyOwnMapper
。但是我要做的是,如果在@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。