弹簧控制器中的简单字符串作为JSON返回值 [英] Simple string as JSON return value in spring rest controller

查看:134
本文介绍了弹簧控制器中的简单字符串作为JSON返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们看看下面的简单测试控制器(与Spring 4.0.3一起使用):

Let's take a look at the following simple test controller (Used with Spring 4.0.3):

@RestController
public class TestController
{
    @RequestMapping("/getList")
    public List<String> getList()
    {
        final List<String> list = new ArrayList<>();
        list.add("1");
        list.add("2");
        return list;
    }

    @RequestMapping("/getString")
    public String getString()
    {
        return "Hello World";
    }
}

理论上,两种控制器方法都应返回有效的JSON。调用第一个控制器方法确实会返回以下JSON数组:

In theory both controller methods should return valid JSON. Calling the first controller method indeed does return the following JSON array:

$ 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字符串:

But the second controller method returns the string without quotes which is not a valid JSON string:

$ curl -i -H "Accept: application/json" http://localhost:8080/getString
HTTP/1.1 200 OK
Content-Type: application/json;charset=UTF-8

Hello World

为什么会这样?可以配置吗?这是一个错误吗?或者我不明白的功能?

Why is that so? Can it be configured? Is it a bug? Or a feature I don't understand?

推荐答案

当你返回 String object,Spring MVC将其解释为放入响应主体的内容,而不是进一步修改它。如果你想要一个实际的字符串作为JSON响应,你需要自己引用它或者明确地通过Jackson运行它。

When you return a String object, Spring MVC interprets that as the content to put in the response body and doesn't modify it further. If you're wanting an actual string to be the JSON response, you'll need to either quote it yourself or run it through Jackson explicitly.

这篇关于弹簧控制器中的简单字符串作为JSON返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆