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

jia*_*ong 76 java json character-encoding apache-httpclient-4.x

我正在尝试使用org.apache.httpcomponentsrest api,它会将json格式数据发布到api.

虽然我得到例外

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

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

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

谢谢!

pyr*_*ade 65

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

{"foo": "bar
baz"}
Run Code Online (Sandbox Code Playgroud)

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

{"foo": "bar\nbaz"}
Run Code Online (Sandbox Code Playgroud)

  • @juanchito 向文字添加换行符会改变文字的内容。您不能仅仅为了可读性而将它们添加到那里,因为它会改变它们的_含义_。将换行符放在标记之间而不是标记内部。不管怎样,当你提交到服务器时,请格式化服务器的内容;之前或之后的人类可读性不相关,应单独处理。 (2认同)

hoa*_*ang 43

运用

mapper.configure(Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
Run Code Online (Sandbox Code Playgroud)

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.
   */
Run Code Online (Sandbox Code Playgroud)

  • 这是Jackson的ObjectMapper,请参见:https://github.com/FasterXML/jackson (2认同)