【发布时间】:2011-02-09 15:54:45
【问题描述】:
我在 android 中为 1.6 构建了一个 JSON 消费者(认为在最旧的版本上构建以获得最大支持是一种很好的做法)。我能够成功检索 1.5-1.6 下的 json。但是,我只是将应用程序扔到我的机器人(2.x)上,现在我收到“org.json.jsonexception:字符处的预期文字值......”。为什么版本不同?我该如何处理?
【问题讨论】:
-
你能提供堆栈跟踪吗?
我在 android 中为 1.6 构建了一个 JSON 消费者(认为在最旧的版本上构建以获得最大支持是一种很好的做法)。我能够成功检索 1.5-1.6 下的 json。但是,我只是将应用程序扔到我的机器人(2.x)上,现在我收到“org.json.jsonexception:字符处的预期文字值......”。为什么版本不同?我该如何处理?
【问题讨论】:
如果你不能让它与那个库一起工作,试试 GSON,这很棒
【讨论】:
我有一种方法可以将 InputStream 转换为 JSON 的字符串表示形式。我需要将子字符串从 (initial, length()-1) 调整为 (initial, length()-2) 以使其在 1.5 和 2.x 中都能正常工作。感谢您的帮助。
private static String convertStreamToString(InputStream is) {
/*
* To convert the InputStream to String we use the BufferedReader.readLine()
* method. We iterate until the BufferedReader returns null which means
* there's no more data to read. Each line will appended to a StringBuilder
* and returned as String.
*/
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// API is defective and does not return correct json response.
// Reformat string response to confirm to expected json response
// return sb.toString();
return "{\"Results\":" + sb.substring(11, sb.length()-2) + "}\n" ;
}
【讨论】:
我收到了同样的错误信息。在我的情况下,结果证明 JSON 库被混淆了,因为返回的 JSON 有引号 (") 转义。这显然混淆了字符串的长度,并导致了异常。
【讨论】: