问题描述
我的问题本质上是对的跟进这个问题.
My question is essentially a follow-up to this question.
@RestController
public class TestController
{
@RequestMapping("/getString")
public String getString()
{
return "Hello World";
}
}
在上面,Spring 会将Hello World"添加到响应正文中.如何将字符串作为 JSON 响应返回?我知道我可以添加引号,但这感觉更像是一种黑客攻击.
In the above, Spring would add "Hello World" into the response body. How can I return a String as a JSON response? I understand that I could add quotes, but that feels more like a hack.
请提供任何示例以帮助解释此概念.
Please provide any examples to help explain this concept.
注意:我不想将其直接写入 HTTP 响应正文,我想以 JSON 格式返回字符串(我正在使用我的控制器使用 RestyGWT 要求响应为有效的 JSON格式).
推荐答案
Either return text/plain
(如 仅从 Spring MVC 3 控制器返回字符串消息) 或者将你的字符串包裹起来
Either return text/plain
(as in Return only string message from Spring MVC 3 Controller) OR wrap your String is some object
public class StringResponse {
private String response;
public StringResponse(String s) {
this.response = s;
}
// get/set omitted...
}
将您的响应类型设置为 MediaType.APPLICATION_JSON_VALUE
(= "application/json"
)
@RequestMapping(value = "/getString", method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
你会得到一个类似于
{ "response" : "your string value" }
这篇关于Spring MVC - 如何在 Rest Controller 中将简单字符串作为 JSON 返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!