How to return a string as valid JSON from a Spring web application?

I have a Spring endpoint for my REST web services application that I want to return a string:

"Unauthorized: token is invalid" 

But my front-end javascript throttles on this:

 JSON.parse("Unauthorized: token is invalid") //Unexpected token U 

How do I get my application to return a valid JSON string? Here is my current code:

 @RequestMapping(value="/401") public ResponseEntity<String> unauthorized() { return new ResponseEntity<String>("Unauthorized: token is invalid", HttpStatus.UNAUTHORIZED); } 
+7
java json spring spring-mvc
source share
3 answers

Return the card instead.

 Map<String,String> result = new HashMap<String,String>(); result.put("message", "Unauthorized..."); return result; 

You do not need to return a ResponseEntity , you can directly return a POJO or collection. Add @ResponseBody to your handler method if you want to return a POJO or collection.

In addition, I would say that it is better to use forward over redirect for errors.

+13
source share

@Neil provides a better alternative to what you are trying to achieve.

However, in response to the question asked, you are close.

The modified code below should give the correct JSON response

 @RequestMapping(value="/401") public ResponseEntity<String> unauthorized() { String json = "[\"Unauthorized\": \"token is invalid\"]"; HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.setContentType(MediaType.APPLICATION_JSON); return new ResponseEntity<String>(json, responseHeaders, HttpStatus.UNAUTHORIZED); } 
+8
source share

All Articles