我有一个 Spring MVC 控制器,具有以下方法:
@RequestMapping(value = "/stringtest", method = RequestMethod.GET)
public String simpletest() throws Exception {
return "test";
}
它位于一个控制器内,如下所示:
@RestController
@RequestMapping(value = "/root")
public class RootController
当我调用返回对象的其他方法时,这些对象由 Jackson 序列化为 JSON。但是这个返回 String 的方法并没有转换为 JSON。如果还不清楚,这里有一个使用curl的示例:
$curl http://localhost:8080/clapi/root/stringtest
test
所以问题是,不带任何引号的“test”不是 JSON 字符串,但我的 REST 客户端需要一个字符串。我希望curl命令显示该字符串并用引号引起来,因此它是合法的JSON:
"test"
我正在使用 Spring WebMVC 4.1.3 和 Jackson 2.4.3。我尝试向 RequestMapping 添加“products”属性,表示它应该返回 JSON。在这种情况下,发送回的 Content-Type 属性是“application/json”,但测试字符串仍然没有被引用。
我可以通过调用 JSON 库将 Java String 转换为 JSON 来解决此问题,但 Spring MVC 和 Jackson 通常会自动执行此操作。但不知怎的,他们并没有在我的例子中这样做。有什么想法我可能配置错误,只是返回测试而不是“测试”?
事实证明,当您使用@EnableWebMvc
注释它默认打开一堆http消息转换器。列表中的第二个是StringHttpMessageConverter
文件说将申请text/*
内容类型。但是,在使用调试器单步执行后,它适用于 String 对象*/*
内容类型 - 显然包括application/json
.
The MappingJackson2HttpMessageConverter
它负责application/json
内容类型在此列表的下方。因此,对于除 String 之外的 Java 对象,都会调用此对象。这就是为什么它适用于 Object 和 Array 类型,但不适用于 String - 尽管有使用 Produce 属性来设置的好建议application/json
内容类型。尽管该内容类型是触发此转换器所必需的,但字符串转换器首先抢走了这项工作!
当我延长WebMvcConfigurationSupport
对于其他一些配置的类,我重写了以下方法以将 Jackson 转换器放在第一位,因此当内容类型为application/json
那么将使用这个而不是字符串转换器:
@Override
protected 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
,所以期待 JSON 的 Angular 客户端现在很高兴。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)