json非法字符有哪些_杰克逊错误“非法字符......只允许常规空格”解析JSON时

I am trying to retrieve JSON data from a URL but get the following error:

Illegal character ((CTRL-CHAR, code 31)):

only regular white space (\r, \n,\t) is allowed between tokens

My code:

final URI uri = new URIBuilder(UrlConstants.SEARCH_URL)

.addParameter("keywords", searchTerm)

.addParameter("count", "50")

.build();

node = new ObjectMapper().readTree(new URL(uri.toString())); <<<<< THROWS THE ERROR

What is going wrong here? And how can I parse this data successfully?

Imports:

import com.google.appengine.repackaged.org.codehaus.jackson.JsonNode;

import com.google.appengine.repackaged.org.codehaus.jackson.map.ObjectMapper;

import com.google.appengine.repackaged.org.codehaus.jackson.node.ArrayNode;

import org.apache.http.client.utils.URIBuilder;

example response

{

meta: {

indexAllowed: false

},

products: {

products: [

{

id: 1,

name: "Apple iPhone 6 16GB 4G LTE GSM Factory Unlocked"

},

{

id: 2,

name: "Apple iPhone 7 8GB 4G LTE GSM Factory Unlocked"

}

]

}

}

解决方案

The message should be pretty self-explanatory:

There is an illegal character (in this case character code 31, i.e. the control code "Unit Separator") in the JSON you are processing.

In other words, the data you are receiving is not proper JSON.

Background:

The JSON spec (RFC 7159) says:

JSON Grammar

A JSON text is a sequence of tokens. The set of tokens includes six

tructural characters, strings, numbers, and three literal names.

[...]

Insignificant whitespace is allowed before or after any of the

six structural characters.

ws = *(

%x20 / ; Space

%x09 / ; Horizontal tab

%x0A / ; Line feed or New line

%x0D ) ; Carriage return

In other words: JSON may contain whitespace between the tokens ("tokens" meaning the part of the JSON, i.e. lists, strings etc.), but "whitespace" is defined to only mean the characters Space, Tab, Line feed and Carriage return.

Your document contains something else (code 31) where only whitespace is allowed, hence is not valid JSON.

To parse this:

Unfortunately, the Jackson library you are using does not offer a way to parse this malformed data. To parse this successfully, you will have to filter the JSON before it is handled by Jackson.

You will probably have to retrieve the (pseudo-)JSON yourself from the REST service, using standard HTTP using, e.g. java.net.HttpUrlConnection. Then suitably filter out "bad" characters, and pass the resulting string to Jackson. How to do this exactly depends on how you use Jackson.

Feel free to ask a separate questions if you are having trouble :-).

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值