java 如何从 Spring Web 应用程序返回字符串作为有效的 JSON?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26874971/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to return a string as valid JSON from Spring web app?
提问by user1007895
I have a Spring endpoint for my REST web services app that I want to return a string:
我的 REST Web 服务应用程序有一个 Spring 端点,我想返回一个字符串:
"Unauthorized: token is invalid"
But my javascript on the front-end chokes on this:
但是我在前端的 javascript 对此感到窒息:
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:
如何让我的应用返回有效的 JSON 字符串?这是我当前的代码:
@RequestMapping(value="/401")
public ResponseEntity<String> unauthorized() {
return new ResponseEntity<String>("Unauthorized: token is invalid", HttpStatus.UNAUTHORIZED);
}
回答by Neil McGuigan
Return a Map instead.
而是返回一个 Map 。
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.
不需要返回 a ResponseEntity
,直接返回 POJO 或集合即可。@ResponseBody
如果要返回 POJO 或集合,请添加到您的处理程序方法。
Also, I'd say it's better to use forward
over redirect
for errors.
另外,我会说最好使用forward
overredirect
来处理错误。
回答by Bill
@Neil presents a better alternative to what you are trying to accomplish.
@Neil 为您要完成的任务提供了更好的替代方案。
In response to the question asked however, you are close.
然而,在回答所提出的问题时,您已经接近了。
The modified code below should produce a valid JSON response
下面修改后的代码应该会产生一个有效的 JSON 响应
@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);
}