小编典典

JSONException:无法将类型为java.lang.String的值转换为JSONObject

json

我有一个JSON文件,其中包含2个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 Parser”,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解析器(5868):解析数据org.json.JSONException:错误//类型为java.lang.String的// STRANGE
SIGN HERE //无法转换为JSONObject

任何人都有关于如何摆脱这些迹象以创建JSONObject的线索?


阅读 466

收藏
2020-07-27

共1个答案

小编典典

看到这个 http://stleary.github.io/JSON-java/org/json/JSONObject.html#JSONObject-
java.lang.String-

JSONObject

public JSONObject(java.lang.String source)
           throws JSONException

从源JSON文本字符串构造JSONObject。这是最常用的JSONObject构造函数。

Parameters:
    source - `A string beginning with { (left brace) and ending with } (right brace).` 
Throws:
    JSONException - If there is a syntax error in the source string or a duplicated key.

您尝试使用以下方法:

new JSONObject("{your string}")
2020-07-27