Jes*_*urn 7 json spring-mvc jackson
我有一个Spring MVC控制器,使用以下方法:
@RequestMapping(value = "/stringtest", method = RequestMethod.GET)
public String simpletest() throws Exception {
return "test";
}
Run Code Online (Sandbox Code Playgroud)
它位于一个控制器内部,如下所示:
@RestController
@RequestMapping(value = "/root")
public class RootController
Run Code Online (Sandbox Code Playgroud)
当我调用其他返回对象的方法时,这些对象被Jackson序列化为JSON.但是这个返回String的方法不会转换为JSON.如果不清楚,这是一个使用curl的例子:
$curl http://localhost:8080/clapi/root/stringtest
test
Run Code Online (Sandbox Code Playgroud)
所以问题是没有任何引号的"test"不是JSON字符串,但我的REST客户端期望一个字符串.我期望curl命令显示带有引号的字符串,所以它是合法的JSON:
"test"
Run Code Online (Sandbox Code Playgroud)
我正在使用Spring WebMVC 4.1.3和Jackson 2.4.3.我试过在RequestMapping中添加一个"produce"属性,说它应该返回JSON.在这种情况下,发回的Content-Type属性是"application/json",但仍未引用测试字符串.
我可以通过调用JSON库将Java String转换为JSON来解决这个问题,但看起来Spring MVC和Jackson通常会自动执行此操作.但不知何故,他们并没有这样做.我可能配置错误的任何想法只是测试回来而不是"测试"?
事实证明,当您使用@EnableWebMvc注释时,它默认打开一堆http消息转换器.列表中的第二个是StringHttpMessageConverter文档所说的text/*内容类型.但是,在使用调试器后,它适用于*/*内容类型的String对象 - 显然包括application/json.
该MappingJackson2HttpMessageConverter负责application/json内容类型进一步此列表上.因此,对于除String之外的Java对象,将调用此对象.这就是它为Object和Array类型工作的原因,但不是String-尽管使用produce属性设置application/json内容类型的好建议.尽管该内容类型是触发此转换器所必需的,但String转换器首先抓住了这个工作!
当我正在WebMvcConfigurationSupport为其他配置扩展类时,我重写了以下方法以将Jackson转换器放在第一位,因此当内容类型为时,application/json将使用此类而不是String转换器:
@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());
}
Run Code Online (Sandbox Code Playgroud)
现在,当我从curl调用测试方法时,我得到了所需的"test"输出而不仅仅是test,所以期待JSON的角度客户端现在很高兴.
| 归档时间: |
|
| 查看次数: |
10937 次 |
| 最近记录: |