【发布时间】:2018-08-30 08:50:48
【问题描述】:
我已经阅读了很多关于在 android 中解析 json 的内容,但我不知道我错过了哪里,因为我认为我做得对,但它一直显示错误
这是我的 JSON:
{
"categories": [
{
"id": 1,
"category_name": "Kiehn, Kohler and Russel",
"created_at": "2018-08-29 05:35:50",
"updated_at": "2018-08-29 05:35:50"
},
{
"id": 2,
"category_name": "Flatley PLC",
"created_at": "2018-08-29 05:35:50",
"updated_at": "2018-08-29 05:35:50"
}]
}
这是我在 android 中的句柄
try {
ArrayList<TagModel> tagdata = new ArrayList<>();
JSONObject object = new JSONObject(response);
//Category
ArrayList<CategoryModel> catedata = new ArrayList<>();
JSONArray catearray = object.getJSONArray("categories");
for (int i = 0; i < catearray.length(); i++) {
JSONObject product = catearray.getJSONObject(i);
CategoryModel recommend_model = new CategoryModel();
recommend_model.setCategoryName(product.getString("category_name"));
recommend_model.setCategoryId(String.valueOf(product.getInt("id")));
catedata.add(recommend_model);
}
} catch (JSONException e) {
e.printStackTrace();
}
错误一直告诉同样的问题:
在 org.json.JSONTokener.syntaxError(JSONTokener.java:449) 在 org.json.JSONTokener.readObject(JSONTokener.java:393) 在 org.json.JSONTokener.nextValue(JSONTokener.java:100) 在 org.json.JSONObject.(JSONObject.java:159) 在 org.json.JSONObject.(JSONObject.java:176) 在 kh.com.example.sopheak_pc.CenturyRecipe.Data.DataClass$1.onResponse(DataClass.java:44) 08-30 06:47:37.283 22712-22712/kh.com.example.sopheak_pc.CenturyRecipe W / System.err:在 kh.com.example.sopheak_pc.CenturyRecipe.Data.DataClass$1.onResponse(DataClass.java:38)
当我调试时,错误从
JSONObject object = new JSONObject(response);
它会发生
catch (JSONException e) {
e.printStackTrace();
}
对不起,如果有点乱,因为我想在所有与错误相关的地方显示谢谢!!!
【问题讨论】:
-
您确定是它在发生错误时尝试解析的 JSON 文本吗?因为那个 JSON 看起来不错。尝试在堆栈跟踪之前打印实际的 JSON,然后测试输出,例如在jsonlint.com
-
正如 Andreas 所说,确保响应变量是有效的 JSON 字符串。非转义引号可能有问题?
-
@Andreas 在你指出之后,我刚刚阅读了我的 Json,我的 json 之间有一点错误,据说 **W/System.err: org.json.JSONException: Unterminated object在 ** 的字符 74646 并在此错误之后显示我的 json
-
@Sam Littlefair 我已经更新了我的第二张错误照片
-
将整个 JSON 复制到在线验证器中,看看它说了什么。如果没有问题,您可能需要转义所有双引号,将
"替换为\"。