W3docs

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.

To return a simple string value as JSON in a Spring MVC @RestController, you should return a Map or a POJO instead of a raw String. Spring MVC serializes raw String return values as plain text by default. Note that @RestController already implies @ResponseBody, so you do not need to add it explicitly.

Here is an example using a Map:

@RestController
public class MyController {

  @GetMapping("/string-as-json")
  public Map<String, String> stringAsJson() {
    Map<String, String> response = new HashMap<>();
    response.put("message", "Hello World");
    return response;
  }
}

This will return a JSON object like this:

{"message":"Hello World"}

For JSON serialization to work, ensure the Jackson library is on your classpath (e.g., spring-boot-starter-web includes it by default).