user1007895
user1007895

Reputation: 3965

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);
}

Upvotes: 7

Views: 15027

Answers (2)

Bill
Bill

Reputation: 2633

@Neil presents a better alternative to what you are trying to accomplish.

In response to the question asked however, you are close.

The modified code below should produce a valid 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);
}

Upvotes: 8

Neil McGuigan
Neil McGuigan

Reputation: 48256

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.

Upvotes: 13

Related Questions