JsonparseException非法的非引用字符((CTRL-CHAR,代码10)

时间:2015-07-21 10:56:42

标签: java json character-encoding apache-httpclient-4.x

我正在尝试使用org.apache.httpcomponents来使用rest api,它会将json格式的数据发布到api。

我遇到异常

  

引起:com.fasterxml.jackson.core.JsonParseException:非法   不带引号的字符((CTRL-CHAR,代码10)):必须使用转义   反斜杠包含在字符串中。

原因是ctrl-char包含在json字符串中。

有没有办法替换它。或者其他解决方案?

谢谢!

5 个答案:

答案 0 :(得分:56)

如果在JSON字符串文字中有换行符(或其他控制字符),则会发生这种情况。

{"foo": "bar
baz"}

如果您是生成数据的人,请在创建字符串文字时将实际换行符替换为转义的换行符"\\n"

{"foo": "bar\nbaz"}

答案 1 :(得分:37)

使用

mapper.configure(Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);

请参阅javadoc

 /**
   * Feature that determines whether parser will allow
   * JSON Strings to contain unquoted control characters
   * (ASCII characters with value less than 32, including
   * tab and line feed characters) or not.
   * If feature is set false, an exception is thrown if such a
   * character is encountered.
   *<p>
   * Since JSON specification requires quoting for all control characters,
   * this is a non-standard feature, and as such disabled by default.
   */

答案 2 :(得分:1)

我建议您使用文本编辑器(如Vim)来查找是否有任何(不可见的)特殊字符或转义字符导致此问题。

或者如果您使用的是Windows,它甚至很简单......只需将代码复制粘贴到Windows记事本中,它很可能会显示任何不可见的不需要的转义字符或换行符等等。修复它们就完成了!

答案 3 :(得分:1)

在Salesforce平台上,此错误是由/引起的,解决方案是将这些错误转义为//

答案 4 :(得分:0)

当您将 JSON 数据发送到服务器时会发生此错误。 也许在您的字符串中,您正尝试使用 /n 添加换行符。

如果在 /n 之前添加 / 应该可以,你需要转义换行符。

"Hello there //n start coding"

结果应该如下

Hello there
start coding
相关问题