我有一个包含 2 个 JSON 数组的 JSON 文件: 一个数组用于路线,一个数组用于景点。
一条路线应该由用户导航到的多个景点组成。 不幸的是,我收到了错误:
JSONException:java.lang.String 类型的值无法转换为 JSONObject
这是我的变量和解析 JSON 文件的代码:
private InputStream is = null;
private String json = "";
private JSONObject jObj = null;
try {
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();
// hier habe ich das JSON-File als String
json = sb.toString();
Log.i("JSON Parser", json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
Log.i("JSON 解析器", json); 显示在生成字符串的开头有一个奇怪的符号:
但错误发生在这里:
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
04-22 14:01:05.043: E/JSON Parser(5868): Error parsing data org.json.JSONException: Value //STRANGE SIGN HERE // of type java.lang.String cannot be converted to JSONObject
任何人都知道如何摆脱这些标志以创建 JSONObject?
最佳答案
原因是在编写字符串时添加了一些不需要的字符。 临时解决方案是
return new JSONObject(json.substring(json.indexOf("{"), json.lastIndexOf("}") + 1));
但尝试删除源字符串上的隐藏字符。
关于android - JSONException : Value of type java. lang.String 无法转换为 JSONObject,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10267910/