检测并解析 JSON 文件中的转义字符“\”?

2023-12-04

我的 JSON 文件数据有问题。我正在使用来自谷歌的以下链接。

http://www.google.com/finance/company_news?q=AAPL&output=json"

当我想解析数据并将其显示在屏幕上时,就会出现问题。由于某种原因,数据未正确解码。

原始数据:

 1.) one which must have set many of the company\x26#39;s board on the edge of their
 2.) Making Less Money From Next \x3cb\x3e...\x3c/b\x3e

当我引入数据时,我会执行以下操作:

DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();        
BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8); 
StringBuilder sb = new StringBuilder();
String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "n");
}
is.close();
json = sb.toString();

我使用 org.json 从 json 文件中提取数据收到的输出如下(注意缺少反斜杠):

1.)one which must have set many of the companyx26#39;s board on the edge of their
2.)Making Less Money From Next x3cbx3e...x3c/bx3e

我目前处理第一个问题的方法是:

JSONRowData.setJTitle((Html.fromHtml((article.getString(TAG_TITLE).replaceAll("x26", "&")))).toString());

但第二个我却忽略了(没有双关语的意思)

我认为这不起作用的原因是反冲用于转义字符。我尝试了许多不同的方法来读取数据,但我没有运气。有没有一种方法可以在不使用正则表达式的情况下导入数据来处理这个问题?


Solution

我们今天的克星:“\​​x26”——ASCII(十六进制表示法)

将原始数据读入字符数组。 apache 的 commons.io 库是实现此目的的好方法。执行此操作后,在 for 循环中读取 char 数组,查找“\”,如果命中,则在下一个数组位置查找“x”。如果再次命中,则取出字符数组中的接下来的两个字符。这两个字符是您的 ASCII 十六进制值。将十六进制转换为十进制形式,然后将十进制转换为字符。获取此字符并将其附加到字符串生成器。

如果没有匹配(与“\”),则将字符附加到字符串生成器。我们现在可以调用.toString()方法并将其转为字符串。

从那里开始,数据可能包含一些 HTML 残余(' 和/或在这种情况下)。使用 Html.fromHtml() 解决了这个问题。


The problem here is that google -- or at least that url -- is supplying invalid JSON1,2. The JSON library, while not rejecting the invalid JSON outright, is parsing it in a "well, let's ignore this \ nonsense and continue" manner. That is, it's not the rendering that is wrong, it is the input which is wrong.

1It is not allowed for \x to appear in a string (except if the \ is itself escaped) as \ (when not escaped) can only be followed by a small set of characters (which does not include x). Escapes for character codes must be done by \u1234 and not \x12.

我能想到的唯一“修复”确实是粗俗的黑客:即读取原始文本并转换\x12 to \u0012。 (其实,这并不是that糟糕的黑客行为,因为不需要考虑上下文相关的东西;然而,它应该not需要!对谷歌感到羞耻。)

2 Extracted invalid JSON string literal:

“苹果公司(纳斯达克股票代码:AAPL)的股价今年继续领先大盘科技股。在周一开始的关键事件之后,该股的价格没有出现重大波动。”

(要使其有效,请将\x26 with \u0026 or &.)

祝你编码愉快,祝你好运:)


在 Java 中,一种[未经测试]的方法可能是使用正则表达式(通过String.replaceAll):

inputString.replaceAll("\\x(\d{2})", "\\u00$1") 
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

检测并解析 JSON 文件中的转义字符“\”? 的相关文章

随机推荐