经过广泛调查,我想分享问题和解决方案。
问题
我有一个运行良好的RestController,只要我负责转换JSON消息。当我尝试使用HttpMessageConverter使转换更加优雅时,客户端将开始接收HTTP 406。
这样可行:
@RequestMapping(value = "/objects", method = RequestMethod.GET)
public Map<String, Object>[] getObjects(@RequestBody Object jsonQuery) {
MyQuery query = new MyConverter().convert(jsonQuery);
// do something with query
}
但是,当我配置转换器时,如下所示:
@Configuration
@EnableWebMvc
@ComponentScan
public class WebConfiguration extends WebMvcConfigurerAdapter {
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> httpMessageConverters) {
httpMessageConverters.add(new QueryMessageConverter(new MediaType("application", "json")));
}
}
这导致HTTP 406:
@RequestMapping(value = "/objects", method = RequestMethod.GET)
public Map<String, Object>[] getObjects(@RequestBody Query Query) {
// do something with query
}
我的pom.xml只引用了spring-boot,而且根本没有提到jackson。
解决方案
见下文
答案 0 :(得分:1)
解决方案非常简单,它是明确注册jackson处理程序:
@Configuration
@EnableWebMvc
@ComponentScan
public class WebConfiguration extends WebMvcConfigurerAdapter {
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> httpMessageConverters) {
httpMessageConverters.add(new QueryMessageConverter(new MediaType("application", "json")));
httpMessageConverters.add(new MappingJackson2HttpMessageConverter());
}
}