How to escape Special Characters in JSON
Asked Answered
R

2

12

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

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

Returnee answered 6/11, 2014 at 9:52 Comment(0)
U
4

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

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.

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>
Ungula answered 1/2, 2016 at 6:5 Comment(0)
A
6

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 :

JSONObject inputParams = JSONObject.fromObject(input);

Hope it helps.

Agrestic answered 22/4, 2015 at 9:48 Comment(0)
U
4

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

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.

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>
Ungula answered 1/2, 2016 at 6:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.