Spring MVC - 如何在Rest Controller中将简单的String作为JSON返回 [英] Spring MVC - How to return simple String as JSON in Rest Controller
问题描述
我的问题基本上是的后续行动这个问题。
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进入响应机构。如何将String作为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 Response主体,我想以JSON格式返回String(我正在使用我的控制器
, RestyGWT ,要求回复为有效的JSON
格式)。
Note: I don't want this written straight to the HTTP Response body, I want to return the String in JSON format (I'm using my Controller with RestyGWT which requires the response to be in valid JSON format).
推荐答案
返回 text / plain
(如仅返回Spring MVC 3中的字符串消息控制器)或包裹你的String是一些对象
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...
}
将您的回复类型设置为 application / json
@RequestMapping(value = "/getString", method = RequestMethod.GET, produces = "application/json")
你将拥有一个类似的JSON
and you'll have a JSON that looks like
{ "response" : "your string value" }
这篇关于Spring MVC - 如何在Rest Controller中将简单的String作为JSON返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!