I have a method in my controller that should returns a String in JSON. It returns JSON for non primitive types:
@RequestMapping(value = "so", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) ResponseEntity<String> so() { return new ResponseEntity<String>("This is a String", HttpStatus.OK); }
The curl response is:
This is a String
A ResponseEntity is returned. We give ResponseEntity a custom status code, headers, and a body. With @ResponseBody , only the body is returned. The headers and status code are provided by Spring.
ResponseEntity represents the whole HTTP response: status code, headers, and body. As a result, we can use it to fully configure the HTTP response.
Create a simple Spring Boot web application and write a controller class files which is used to redirects into the HTML file to consumes the RESTful web services. We need to add the Spring Boot starter Thymeleaf and Web dependency in our build configuration file. For Maven users, add the below dependencies in your pom.
@RequestMapping(value = "so", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public @ResponseBody String so() { return "This is a String"; }
The root of the problem is that Spring (via ResponseEntity, RestController, and/or ResponseBody) will use the contents of the string as the raw response value, rather than treating the string as JSON value to be encoded. This is true even when the controller method uses produces = MediaType.APPLICATION_JSON_VALUE
, as in the question here.
It's essentially like the difference between the following:
// yields: This is a String System.out.println("This is a String"); // yields: "This is a String" System.out.println("\"This is a String\"");
The first output cannot be parsed as JSON, but the second output can.
Something like '"'+myString+'"'
is probably not a good idea however, as that won't handle proper escaping of double-quotes within the string and will not produce valid JSON for any such string.
One way to handle this would be to embed your string inside an object or list, so that you're not passing a raw string to Spring. However, that changes the format of your output, and really there's no good reason not to be able to return a properly-encoded JSON string if that's what you want to do. If that's what you want, the best way to handle it is via a JSON formatter such as Json or Google Gson. Here's how it might look with Gson:
import com.google.gson.Gson; @RestController public class MyController private static final Gson gson = new Gson(); @RequestMapping(value = "so", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) ResponseEntity<String> so() { return ResponseEntity.ok(gson.toJson("This is a String")); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With