javajsonspringrestspring-mvc

Spring MVC - How to return simple String as JSON in Rest Controller


My question is essentially a follow-up to this question.

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

In the above, Spring would add "Hello World" into the response body. How can I return a String as a JSON response? I understand that I could add quotes, but that feels more like a hack.

Please provide any examples to help explain this concept.

Note: I don't want this written straight to the HTTP Response body, I want to return the String in JSON format (I'm using my Controller with RestyGWT which requires the response to be in valid JSON format).


Solution

  • Either return text/plain (as in Return only string message from Spring MVC 3 Controller) OR wrap your String in some object

    public class StringResponse {
    
        private String response;
    
        public StringResponse(String s) { 
           this.response = s;
        }
    
        // get/set omitted...
    }
    

    Set your response type to MediaType.APPLICATION_JSON_VALUE (= "application/json")

    @RequestMapping(value = "/getString", method = RequestMethod.GET,
                    produces = MediaType.APPLICATION_JSON_VALUE)
    

    and you'll have a JSON that looks like

    {  "response" : "your string value" }