【问题标题】:Android: Parsing JSONArray of a JSONObject but still get syntax ErrorAndroid:解析 JSONObject 的 JSONArray 但仍然出现语法错误
【发布时间】: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 看起来不错。尝试在堆栈跟踪之前打印实际的 JSON,然后测试输出,例如在jsonlint.com
  • 正如 Andreas 所说,确保响应变量是有效的 JSON 字符串。非转义引号可能有问题?
  • @Andreas 在你指出之后,我刚刚阅读了我的 Json,我的 json 之间有一点错误,据说 **W/System.err: org.json.JSONException: Unterminated object在 ** 的字符 74646 并在此错误之后显示我的 json
  • @Sam Littlefair 我已经更新了我的第二张错误照片
  • 将整个 JSON 复制到在线验证器中,看看它说了什么。如果没有问题,您可能需要转义所有双引号,将" 替换为\"

标签: java android


【解决方案1】:

@Andreas 和@Sam Littlefair 提到我的 json 在字符串中包含“,”,所以我清理了我的数据并输入了简单的数据,现在它工作正常!谢谢你们两个!

【讨论】:

  • 别担心,很高兴你把它整理好了!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-06
  • 2016-03-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多