事实证明,当您使用
@EnableWebMvc注释时,默认情况下它将打开一堆http消息转换器。列表中的第二个是
StringHttpMessageConverter文档说明将用于
text*内容类型的String对象-
显然包括
application/json。
该
MappingJackson2HttpMessageConverter负责
application/json内容类型是这个名单上进一步下跌。因此,对于除String之外的Java对象,将调用此对象。这就是为什么它适用于对象和数组类型,而不适用于字符串的原因,尽管有很好的建议使用Produces属性设置
application/json内容类型。尽管必须使用该内容类型才能触发此转换器,但String转换器首先抢占了工作!
当我将
WebMvcConfigurationSupport类扩展为其他配置时,我覆盖了以下方法以将Jackson转换器放在第一位,因此,当content-
type为true时,
application/json将使用此方法代替String转换器:
@Overrideprotected void configureMessageConverters( List<HttpMessageConverter<?>> converters) { // put the jackson converter to the front of the list so that application/json content-type strings will be treated as JSON converters.add(new MappingJackson2HttpMessageConverter()); // and probably needs a string converter too for text/plain content-type strings to be properly handled converters.add(new StringHttpMessageConverter());}现在,当我从curl调用test方法时,我得到的是所需的
"test"输出,而不是just
test,因此期望JSON的角度客户端现在很高兴。



