java 如何在 JSON 中转义特殊字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26776311/
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 escape Special Characters in JSON
提问by hpandalai
We have a form which has a long paragraph for a scienctific application that contains characters like symbol beta(?-arrestin) etc. We have a JSON service running on Mule that takes the data and persists to an oracle database. This particular element with long paragraph is giving me an error in RAML/JSON. Below is the error
我们有一个表单,其中包含一个包含符号 beta(?-arrestin) 等字符的科学应用程序的长段落。我们有一个在 Mule 上运行的 JSON 服务,它获取数据并保存到 oracle 数据库中。这个带有长段落的特定元素在 RAML/JSON 中给了我一个错误。下面是错误
com.fasterxml.Hymanson.core.JsonParseException: Illegal unquoted character ((CTRL-CHAR, code 9)): has to be escaped using backslash to be included in string value
The form element to which the scientists write we have no control. So on the Mule side how can we escape these characters automagically like java has URLEncoded. Many Thanks
科学家们编写的表单元素我们无法控制。因此,在 Mule 方面,我们如何像 java 具有 URLEncoded 那样自动转义这些字符。非常感谢
采纳答案by sshaw
In your case it looks like the incoming data is malformed. It must be in an encoding supported by the JSON spec: UTF-8 (default), UTF-16, or UTF-32. So not sure if the following is applicable. Nevertheless...
在您的情况下,传入数据的格式似乎不正确。它必须采用JSON 规范支持的编码:UTF-8(默认)、UTF-16 或 UTF-32。所以不确定以下是否适用。尽管如此...
For most apps I would recommend JSON to Object mapping, which will take care of the escaping. Otherwise, you can call Hymanson's (the JSON library used by Mule) String escape methoddirectly.
对于大多数应用程序,我会推荐JSON to Object mapping,它将负责转义。否则,您可以直接调用 Hymanson 的(Mule 使用的 JSON 库)字符串转义方法。
Here's an example that you can use in MEL. String.valueOf
is necessary because quoteAsString
returns char[]
:
这是您可以在 MEL 中使用的示例。String.valueOf
是必要的,因为quoteAsString
返回char[]
:
<configuration>
<expression-language>
<import class="org.codehaus.Hymanson.io.JsonStringEncoder" />
<global-functions>
def quoteJSONString(s) {
String.valueOf(JsonStringEncoder.getInstance().quoteAsString(s))
}
</global-functions>
</expression-language>
</configuration>
回答by kaulmonish
At the target you can receive the data as text/plain.
在目标处,您可以以文本/纯文本形式接收数据。
Clean it by running :
通过运行清洁它:
input.replaceAll("\p{Cc}", "").
Convert it back to JSON data using any JSON library :
使用任何 JSON 库将其转换回 JSON 数据:
JSONObject inputParams = JSONObject.fromObject(input);
Hope it helps.
希望能帮助到你。