我在处理一个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());
第二个问题我不太清楚(无恶意)。
我猜这个不起作用的原因是反斜杠被用作转义字符。我尝试了许多不同的方法来读取数据,但都没有成功。有没有一种方法可以导入数据以处理这个问题,而不使用正则表达式?
解决方案
我们今天的宿敌:"\x26" -- ASCII(十六进制表示法)
将原始数据读入Char数组。apache的commons.io库是实现此操作的好方法。一旦完成这一步骤,使用for循环读取Char数组,查找“\”,如果找到,则在下一个数组位置查找“x”。如果再次找到,则获取Char数组中的下两个字符。这两个字符是您的ASCII十六进制值。将十六进制转换为十进制形式,然后将十进制强制转换为Char。将此字符附加到字符串构建器。
如果没有匹配项(带有“\”),则将Char附加到字符串构建器。现在我们可以调用.toString()
方法并将其转换为字符串。
从那里开始,数据可能包含一些HTML残留物(在本例中为'和/或)。使用Html.fromHtml()来处理这些内容。