让我们看看下面的简单测试控制器(与Spring 4.0.3一起使用):
@RestController
public class TestController
{
@RequestMapping("/getList")
public List getList()
{
final List list = new ArrayList<>();
list.add("1");
list.add("2");
return list;
}
@RequestMapping("/getString")
public String getString()
{
return "Hello World";
}
}
理论上,两种控制器方法都应该返回有效的JSON.调用第一个控制器方法确实会返回以下JSON数组:
$curl -i -H "Accept: application/json" http://localhost:8080/getList
HTTP/1.1 200 OK
Content-Type: application/json;charset=UTF-8
["1","2"]
但第二个控制器方法返回没有引号的字符串,这不是有效的JSON字符串:
$curl -i -H "Accept: application/json" http://localhost:8080/getString
HTTP/1.1 200 OK
Content-Type: application/json;charset=UTF-8
Hello World
为什么会这样?可以配置吗?这是一个错误吗?或者我不明白的功能?
解决方法:
当您返回String对象时,Spring MVC会将其解释为要放入响应正文的内容,而不会进一步修改它.如果您想要一个实际的字符串作为JSON响应,您需要自己引用它或明确地通过Jackson运行它.
标签:java,spring,json,spring-mvc,jackson
来源: https://codeday.me/bug/20191002/1842620.html