android - JSONException : Value of type java. lang.String 无法转换为 JSONObject

标签 android json parsing

我有一个包含 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); 显示在生成字符串的开头有一个奇怪的符号:enter image description here

但错误发生在这里:

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/

相关文章:

java - 无法将 json 转换为 java pojo 类?

android - 多个六边形按钮

javascript - mustache 模板不在表 tbody 内呈现

parsing - 无法用 LL 表示的 LR 语法示例?

c# - 结合序列化和语法解析的方法?

java - 自定义适配器使我的应用程序崩溃 (NullPointerException) 我已经尝试了所有方法?

Android简单XML解析

python - 确保 POST 数据是有效的 JSON

javascript - Openlayers - 缩放至图层

java - 如何将长字符串在 "),"处分割成行?