有一种干净的方法可以在 Spring Web API 中将字符串作为 json 返回吗? [英] There is a clean way to return string as json in a Spring Web API?

查看:68
本文介绍了有一种干净的方法可以在 Spring Web API 中将字符串作为 json 返回吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我必须实现如下:

For example, I had to implement as below:

@RequestMapping(value = "/get-string", method = {RequestMethod.GET})
public @ResponseBody String getString() {
    return "Hello World!";
}

Ajax 在 JS 文件中调用 action 时,收到的响应为:HelloWorld.因此,如果 Ajax 请求配置为仅接收 json 编码的响应,我会收到标准解码错误.为了在服务器端解决这个问题,我需要接收"HelloWorld".

When the action is called by Ajax in a JS file, the response received is: HelloWorld. So, if the Ajax request is configured to only receive json encoded responses, I receive the standard deconding error. To solve this problem in server-side, I need to receive "HelloWorld".

我的问题是:有一种干净的方法可以做到这一点,而不是仅仅更改为下面的字符串返回的字符串?

My question is: There is a clean way I can do this, instead of just changing the string returned for the string below?

    ...
    return "\"Hello World!\"";
}

更新说明:在提出这个问题时,我对返回 JSON 映射而不是像我以前想要的那样返回单个字符串的解决方案感到满意.

UPDATE NOTE: In the time of this question, I was satisfied with the solution of returning a JSON map instead of a single string, as I wanted previously.

但现在,我花了一些时间搜索这个,并试图了解更多关于 JSON 模式的信息.

But now, I've spent some time searching about this, and trying to understand more about JSON patterns.

首先,我发现我的问题重复了这些问题一个两个三个.正确的 answer 表示问题在于 Spring Boot 的默认序列化程序(Jackson 的库)处理字符串值(序列化时)作为原始 JSON 字符串,因此它返回没有双引号的值,而不是像我期望的那样添加.

First of all, I found that my question is duplicated of these questions one, two and three. The correct answer says that the problem is with Spring Boot's default serializer (Jackson's library) that treats a string value (when serializing) as a raw JSON string, so it returns the value without double quotes instead of adding, as I was expecting.

公平地说,我会选择 Bh​​argav 的答案,这更接近于我在找什么.来自 ddbullfrogRohaNayak 的答案 是正确的,但它们没有正确解决我的问题.Ademir Constantino 的 评论 也是正确的,他说使用纯文本/文本而不是 json 格式,使用这个 参考.Luay Absulraheem 的 answer 是配置操作的正确方法,但它没有按预期方式工作,它继续将字符串作为原始 json 发送.非常感谢您的回答!

And to be fair, I will choose the Bhargav's answer, that reached closer to what I was looking for. The answers from ddbullfrog and RohaNayak are correct, but they do not solve my problem correctly. Ademir Constantino's comment is correct too, he says to use plain/text instead of json format, using this reference. The Luay Absulraheem's answer is a correct way to config the action, but it doesn't work the way wanted, it continue to send the string as raw json. Thank you very much for your answers!

此外,可以自定义 Spring Boot 以使用 Gson 作为其序列化程序,正如在此 文章.在您的项目上安装 Gson 依赖项后,您只需在 application.properties 文件中添加以下行:

Additionally, it is possible to customize the Spring Boot to use Gson as its serializer, as can be seen on this article. After installing Gson dependency on your project, you just have to add this line on your application.properties file:

...
spring.http.converters.preferred-json-mapper=gson

这样就不用每次要发送字符串值都解析由 Spring Boot 序列化,并且不要在 AJAX 处理程序上没有双引号的情况下接收它.

In this way, you don't have to parse every time you want to send a string value to be serialized by Spring Boot and don't receive it without double quotes on your AJAX handler.

我试图实现我在 ASP.NET MVC 上得到的相同行为,它使用了 JSON.NET library 执行序列化.这一点以及 AJAX 接受单个字符串(例如hello world")作为 JSON 的事实使我对 JSON 模式进行了更深入的研究.

I was trying to achieve the same behavior I get on ASP.NET MVC, which used the JSON.NET library to perform serialization. This and the fact that AJAX accepts a single string (e.g. "hello world") as a JSON, have made me do a deeper research about JSON patterns.

JSON 格式有不止一个标准"定义.正如在此堆栈的其他问题中所讨论的那样,当前的互联网标准"来自JSON 值由 RFC-8259 定义,如文档第 5 页所述:

There is more than one "standard" definition of a JSON format. As it's discussed on this Stack's other question, the current "INTERNET STANDARD" from JSON values is defined by RFC-8259 as it is said on page 5 of the document:

JSON 值必须是对象、数组、数字或字符串,或以下之一以下三个字面名称:

A JSON value MUST be an object, array, number, or string, or one of the following three literal names:

  • 真实

如上所示,在旧标准中,JSON 可以是一种比以前更广泛的数据类型.

As can be seen above, a JSON can be one wider range of data types than before in older standards.

更新注意:另一种选择是返回一个 char[] 而不是一个字符串实例.这样,Spring Boot 就不会识别为原始 JSON 字符串:

UPDATE NOTE: Another alternative is to return a char[] instead of a String instance. In this way, Spring Boot will not recognize as raw JSON string:

@RequestMapping(value = "/get-string", method = {RequestMethod.GET})
public @ResponseBody char[] getString() {
    return "Hello World!".toCharArray();
}

推荐答案

是的,您可以使用 gson 或 jackson 等库将字符串转换为 JSON,从而为您提供如下所示的 json 输出.

Yes,you can use libraries like gson or jackson to convert your strings into JSON, there by giving you a json output like below.

Gson gson= new GsonBuilder().create();
    gson.toJson(Your String);

另外,不要忘记添加produces = MediaType.APPLICATION_JSON_VALUE 到暴露的方法,以便spring知道需要产生什么样的o/p.

Also, dont forget to add produces = MediaType.APPLICATION_JSON_VALUE to the method exposed so that spring knows what kind of o/p needs to be produced.

这篇关于有一种干净的方法可以在 Spring Web API 中将字符串作为 json 返回吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆