Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

"Unauthorized: token is invalid"

But my javascript on the front-end chokes on this:

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

How do I get my app 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);
}
like image 849
user1007895 Avatar asked Nov 11 '14 21:11

user1007895


1 Answers

Return a Map instead.

Map<String,String> result = new HashMap<String,String>();

result.put("message", "Unauthorized...");

return result;

You don't 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.

Also, I'd say it's better to use forward over redirect for errors.

like image 109
Neil McGuigan Avatar answered Sep 19 '22 06:09

Neil McGuigan