我的 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() 解决了这个问题。