将JSONArray转换为JSONObject时出现ClassCastException

时间:2013-09-30 03:45:50

标签: java android json

这是我的代码段:

    jArray = jChild.getJSONArray("users");
                    for (int i = 0; i < jArray.length(); i++) {
                        JSONObject jObject = (JSONObject) jArray.get(i);    //Exception thrown in this line

}

修改

logcat的:

09-30 09:06:23.404: E/AndroidRuntime(4011): java.lang.RuntimeException: An error occured while executing doInBackground()
09-30 09:06:23.404: E/AndroidRuntime(4011):     at android.os.AsyncTask$3.done(AsyncTask.java:200)
09-30 09:06:23.404: E/AndroidRuntime(4011): Caused by: java.lang.ClassCastException: java.lang.String
09-30 09:06:23.404: E/AndroidRuntime(4011):     at com.example.DbAccess.loadMonthView(DbAccess.java:196)

这是我的jsonArray:

 [{"uid":"6","status":"absent","name":"xyz"},{"uid":"7","status":"absent","name":"abc Paul"}]

我想从JSONObject检索JSONArray

2 个答案:

答案 0 :(得分:2)

[ // represents json array node
    {     // represents json obeject node  
        "uid": "6",
        "status": "absent",
        "name": "xyz"
    },
    {
        "uid": "7",
        "status": "absent",
        "name": "abc Paul"
    }
]

你拥有的是JSONArray。您需要解析值并获取字符串。

     JSONArray jr = new JSONArray("myjsonstring");
     for(int i=0;i<jr.length();j++)
     {
     JSONOBject jb = jr.getJSONObject(i);
     String uid = jb.getString("uid");
     String status = jb.getString("status");
     String name = jb.getString("name");  
     } 

答案 1 :(得分:0)

您的Json文件在顶层有一个数组。当JSonParser解析它时,它将它作为JSONArray返回。您正在尝试将其转换为JSONObject(这类似于地图或字典。)您需要做的是:

Object obj;
try {

    obj = parser.parse(sCurrentLine);
    JSONArray jsonArray = (JSONArray) obj;
    for(obj : jsonArray){//not sure of the exact syntax, I don't have an IDE in front of me.
        JSONObject jsonObject = (JSONObject)obj;
        JSONObject realTitle = (JSONObject)jsonObject.get("0");
        String name = (String) realTitle.get("title");
    }


} catch (ParseException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}