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

To return a simple string as JSON in a Spring MVC Rest Controller, you can use the @ResponseBody annotation and return the string directly. The string will be automatically converted to a JSON object.

Here is an example:

@RestController
public class MyController {

  @GetMapping("/string-as-json")
  @ResponseBody
  public String stringAsJson() {
    return "Hello World";
  }
}

This will return a JSON object like this:

{"message":"Hello World"}

If you want to return a string as a plain text response, you can use the @ResponseBody annotation and set the Content-Type header to text/plain. Here is an example:

@RestController
public class MyController {

  @GetMapping("/string-as-plain-text")
  @ResponseBody
  public String stringAsPlainText(HttpServletResponse response) {
    response.setContentType("text/plain");
    return "Hello World";
  }
}

This will return a plain text response with the string "Hello World".