Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple string as JSON return value in spring rest controller

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";
    }
}

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"]

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?

like image 312
kayahr Avatar asked May 10 '14 13:05

kayahr


People also ask

How do you return a string as a response entity?

ResponseEntity example to return String In case of String, you can just set ResponseEntity's body with String value. In the following example, we are using a shortcut for ResponseEntity to set body content as String and HTTP status as Ok (200).

How can I convert JSON to string?

Use the JavaScript function JSON.stringify() to convert it into a string. const myJSON = JSON.stringify(obj); The result will be a string following the JSON notation.


1 Answers

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.

like image 53
chrylis -cautiouslyoptimistic- Avatar answered Oct 12 '22 13:10

chrylis -cautiouslyoptimistic-