本文介绍了Spring MVC - 如何在Rest Controller中将简单的String作为JSON返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题基本上是问题。

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.


推荐答案

返回 text / plain (如)或包裹你的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返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-27 20:44
查看更多