Java JsonParseException : 非法的未加引号的字符((CTRL-CHAR,代码 10)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31537153/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 11:13:19  来源:igfitidea点击:

JsonParseException : Illegal unquoted character ((CTRL-CHAR, code 10)

javajsoncharacter-encodingapache-httpclient-4.x

提问by jian zhong

I'm trying to use org.apache.httpcomponentsto consume a Rest API, which will post JSON format data to API.

我正在尝试使用org.apache.httpcomponentsRest API,它将 JSON 格式的数据发布到 API。

I get this exception:

我得到这个例外:

Caused by: com.fasterxml.Hymanson.core.JsonParseException: Illegal unquoted character ((CTRL-CHAR, code 10)): has to be escaped using backslash to be included in string.

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

The reason is because ctrl-charis included in the JSON string.

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

Is there any way to replace this or some other solution?

有什么办法可以代替这个或其他一些解决方案吗?

回答by pyrospade

This can happen if you have a newline (or other control character) in a JSON string literal.

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

{"foo": "bar
baz"}

If you are the one producing the data, replace actual newlines with escaped ones "\\n"when creating your string literals.

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

{"foo": "bar\nbaz"}

回答by hoang

Using

使用

mapper.configure(Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);

See javadoc:

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

回答by Daniel Sokolowski

On Salesforce platform this error is caused by /, the solution is to escape these as //.

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