0

我看不出我的 JSON 有什么问题,我收到无法将其转换为 JSONObject 的错误。我在论坛上搜索,但我找不到答案。

代码(解析):

JSONObject json = new JSONObject(result.toString().replace("\\", " "));
                    JSONArray jArray = json.getJSONArray("timetable");

                    for(int i = 0; i < jArray.length(); i++) {
                        JSONObject json_data = jArray.getJSONObject(i);
                        String class_school = json_data.getString("class");
                        String teacher = json_data.getString("teacher");
                        String subject = json_data.getString("subject");
                        String room = json_data.getString("room");
                        timetList.add(new TimeTable(subject, class_school + " " + teacher + " " + " " + room));
                    }

JSON:

{"timetable":[{"teacher":"Woh","subject":"BVH","room":"017","change":"no"},{"teacher":"Rrl","subject":"BI","room":"045","change":"no"},{"teacher":"Ajg","subject":"WI","room":"019","change":"no"},{"teacher":"Sgh","subject":"NE","room":"119","change":"no"},{"teacher":"Rom","subject":"FA","room":"116","change":"no"},{"teacher":"Her","subject":"GS","room":"127","change":"no"},"free","free"]}

日志猫:

03-29 15:06:11.356: E/error(822): Value free at 6 of type java.lang.String cannot be converted to JSONObject
4

3 回答 3

1

在我看来,您正在尝试将最后两个条目(“免费”,“免费”)解析为 JSONObject。如果由于某种原因您需要添加空条目,请使用 {}。

考虑使用 optString 而不是 getString (或使用 try catch 语句来处理异常)

于 2013-03-29T15:27:13.527 回答
0

问题在String. 你的JSON字符串坏了,这是

java.lang.String 类型为 6 的自由值无法转换为 JSONObject

看看你的字符串:

{
  "timetable": [
                {"teacher":"Woh","subject":"BVH","room":"017","change":"no"},
                {"teacher":"Rrl","subject":"BI","room":"045","change":"no"},
                {"teacher":"Ajg","subject":"WI","room":"019","change":"no"},
                {"teacher":"Sgh","subject":"NE","room":"119","change":"no"},
                {"teacher":"Rom","subject":"FA","room":"116","change":"no"},
                {"teacher":"Her","subject":"GS","room":"127","change":"no"},

                "free","free"
              ]
}

您需要删除此意外序列:

"free","free"

最后一个逗号JSONObject加上教师的价值Her,它应该可以工作。

于 2013-03-29T15:29:05.253 回答
0

您的字符串是有效的 JSON;然而

JSONObject json_data = jArray.getJSONObject(i);

假设数组位置的实体i是 JSON 对象。“free”是一个字符串,它不是 JSON 中的对象类型(不被 {} 包围),getJSONObject(i)当您尝试从字符串中创建对象时会引发此异常。

可以使用 提取字符串jArray.getString(i),但真正的技巧是确定 position 实体的类型i。您可以尝试使用泛型jArray.get(i),然后自省返回值以确定其类型。

于 2013-04-10T18:20:00.580 回答