Java 简单字符串作为弹簧休息控制器中的 JSON 返回值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23581619/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 00:07:51  来源:igfitidea点击:

Simple string as JSON return value in spring rest controller

javajsonspringspring-mvcHymanson

提问by kayahr

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

我们来看看以下简单的测试控制器(与 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";
    }
}

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

理论上,两个控制器方法都应该返回有效的 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"]

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

但是第二个控制器方法返回不带引号的字符串,它不是有效的 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

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

为什么呢?可以配置吗?这是一个错误吗?还是我不明白的功能?

采纳答案by chrylis -cautiouslyoptimistic-

When you return a Stringobject, 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 Hymanson explicitly.

当您返回一个String对象时,Spring MVC 会将其解释为要放入响应主体的内容,并且不会进一步修改它。如果您想要一个实际的字符串作为 JSON 响应,您需要自己引用它或明确地通过 Hymanson 运行它。

回答by d0x

You can remove the StringHttpMessageConverterwhich is registered before the Hymanson converter, - like mentioned in the comment.

您可以删除在StringHttpMessageConverterHymanson 转换器之前注册的 , - 就像评论中提到的那样。

/**
 * Unregister the default {@link StringHttpMessageConverter} as we want
 * Strings to be handled by the JSON converter.
 *
 * Our MappingHymanson2HttpMessageConverter will deal with strings.
 *
 * @param converters
 *            List of already configured converters
 */
@Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
    converters.removeIf(converter -> converter instanceof StringHttpMessageConverter);
}

回答by Gopal

If you want to 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 Hymanson explicitly.

如果您想返回一个 String 对象,Spring MVC 会将其解释为要放入响应正文的内容,并且不会进一步修改它。如果您想要一个实际的字符串作为 JSON 响应,您需要自己引用它或明确地通过 Hymanson 运行它。

@RestController
public class TestController
{
   @RequestMapping("/getString")
   public String getString()
  {
    return JSONObject.quote("Hello World");
  }
}

回答by Neeraj Bansal

Here are the steps that I did to achieve this :

以下是我为实现这一目标所做的步骤:

  1. Add dependency in pom file:

    <dependency>
        <groupId>com.fasterxml.Hymanson.core</groupId>
        <artifactId>Hymanson-databind</artifactId>
        <version>2.9.3</version>
    </dependency>
    
  2. Put @ResponseBodyannotation on your method like this:

    @RequestMapping(value = "/getCountries", method = RequestMethod.GET)    
    @ResponseBody    
    public List<Country> getCountries() {    
        return countryDAO.list();    
    }
    
  1. 在 pom 文件中添加依赖:

    <dependency>
        <groupId>com.fasterxml.Hymanson.core</groupId>
        <artifactId>Hymanson-databind</artifactId>
        <version>2.9.3</version>
    </dependency>
    
  2. @ResponseBody注释你的方法是这样的:

    @RequestMapping(value = "/getCountries", method = RequestMethod.GET)    
    @ResponseBody    
    public List<Country> getCountries() {    
        return countryDAO.list();    
    }