如何在JSON中转义特殊字符

如何在JSON中转义特殊字符

本文介绍了如何在JSON中转义特殊字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个表格,其中包含一个scienctific应用程序的长段落,其中包含符号beta(ß-arrestin)等字符。我们在Mule上运行一个JSON服务,它接收数据并持久存储到oracle数据库。这个带有长段的特殊元素在RAML / JSON中给出了一个错误。以下是错误

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

com.fasterxml.jackson.core.JsonParseException: Illegal unquoted character ((CTRL-CHAR, code 9)): has to be escaped using backslash to be included in string value

科学家的表单元素写我们无法控制。所以在Mule方面,我们如何自动地逃避这些字符,就像java具有URLEncoded一样。非常感谢

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

推荐答案

在您的情况下,看起来输入数据格式不正确。它必须位于:UTF-8(默认),UTF-16或UTF-32。所以不确定以下内容是否适用。然而......

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...

对于大多数应用程序,我建议,它将负责转义。否则,您可以调用Jackson(Mule使用的JSON库)。

For most apps I would recommend JSON to Object mapping, which will take care of the escaping. Otherwise, you can call Jackson's (the JSON library used by Mule) String escape method directly.

以下是您可以在MEL中使用的示例。 String.valueOf 是必要的,因为 quoteAsString 返回 char []

Here's an example that you can use in MEL. String.valueOf is necessary because quoteAsString returns char[]:

<configuration>
  <expression-language>
    <import class="org.codehaus.jackson.io.JsonStringEncoder" />
    <global-functions>
      def quoteJSONString(s) {
        String.valueOf(JsonStringEncoder.getInstance().quoteAsString(s))
      }
    </global-functions>
  </expression-language>
</configuration>

这篇关于如何在JSON中转义特殊字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 12:46