【问题标题】:JSON Exception: java.lang.String cannot be converted to JSONObjectJSON 异常:java.lang.String 无法转换为 JSONObject
【发布时间】:2015-02-04 02:31:13
【问题描述】:

我有一个 JSON 异常被抛出,我不知道它为什么被抛出。我已经查看了几乎所有与我类似的其他问题,但我认为我的问题不同。所以我从网页上得到一个 JSONArray,它发送的 JSON 是有效的(我用验证器检查了它)。当我在 JSONArray 上执行 getJSONObject 时抛出异常。

这正是它所说的(个人信息已加星标):

org.json.JSONException: Value  [{"name":"*****","profilePicture":"*****"}] at 0 of type java.lang.String cannot be converted to JSONObject

这是我的 Java 代码:

 protected Void doInBackground(JSONObject... params) {
        JSONObject jsonObject = params[0];
        ClientServerInterface clientServerInterface = new ClientServerInterface();
        JSONArray attendanceDetails = clientServerInterface.postData("http://54.164.136.46/get_attendance.php", jsonObject);
        Log.e("Attendance Details: ", attendanceDetails.toString());

        nameAttendees = new String[attendanceDetails.length()];
        pictureAttendees = new String[attendanceDetails.length()];

        JSONObject jobj = null;
 for(int i = 0; i < attendanceDetails.length(); i++)
        {
            try {
                jobj = attendanceDetails.getJSONObject(i);
                nameAttendees[i] = jobj.getString("name");
                pictureAttendees[i] = jobj.getString("profilePicture");
            } catch (JSONException e) {
                e.printStackTrace();
            }

错误发生在我去的那一行:

jobj = attendanceDetails.getJSONObject(i);

非常感谢任何帮助。

【问题讨论】:

  • 这段代码看起来是正确的。你能在 for 循环上面再写几行吗?
  • 你能发布你试图解析的 JSON 吗?看起来您尝试解析的元素是一个字符串 ["name"],而您期望的是一个对象 [{"name": "name"}]
  • JSON 在异常中的 OP 中
  • 在循环上方添加代码
  • 哦,我看到了一些奇怪的东西。我打印出 JSONArray,它是这样的:[" [{\"name\":\"*****\",\"profilePicture\":\"*****\"}]\n"]

标签: android json


【解决方案1】:

试试这个:

for(int i = 0; i < attendanceDetails.length(); i++)
    {
        try {
            JSONArray hello = new JSONArray(attendanceDetails.getJSONArray(i));
            JSONObject jObject = new  JSONObject(hello.get(i).toString());
            nameAttendees[i] = jObject.getString("name");
            pictureAttendees[i] = jObject.getString("profilePicture");
        } catch (JSONException e) {
            e.printStackTrace();
        }

【讨论】:

  • 变量 jobj 是 JSONObject 类型。那么我应该将它转换为 JSONObject,因为 .get 返回类型 Object?
  • 现在我得到了这个异常:java.lang.String cannot be cast to org.json.JSONObject
  • 你不能。当你使用get函数时。你可以在你的例子中得到一个字符串。虽然字符串是一个对象。它可以转换为JSONObject,除非它是一个真实的对象而不是子类对象。
  • 这是我所做的:JSONObject jObject = new JSONObject(attendanceDetails.get(i).toString()); nameAttendees[i] = jObject.getString("name"); pictureAttendees[i] = jObject.getString("profilePicture"); 错误是 JSONArray 无法转换为 JSONObject
  • JSONArray hello = new JSONArray(attendanceDetails.getJSONArray(i));JSONObject jObject = new JSONObject(hello.get(i).toString());
猜你喜欢
  • 2018-02-22
  • 2021-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多