无法从jsonobject提取jsonarray

时间:2019-07-02 17:11:57

标签: java arrays json retrofit2

我一直在努力应对使用翻新服务器的响应。

我有来自服务器的json响应

{
    "success": true,
    "message": "Your Requests",
    "data": {
        "requests": [
            {
                "_id": "5d163a5ed2399f8be6d8d867",
                "created": "2019-06-28T16:03:42.463Z",
                "pickupCoordinates": [
                    8.0099,
                    6.0909
                ],
                "destinationCoordinates": [
                    9.088788,
                    3.099403
                ],
                "customerName": "Seun Akinbode",
                "pickupAddress": "Lekki",
                "destinationAddress": "Ajah",
                "accessCode": "3334",
                "busPlate": "DD222RR",
                "flaName": "Simi",
                "flaEmail": "awele@kobo360.com",
                "__v": 0
            } ]
}

我使用下面的类来解析json,但不幸的是,它无法将数组requests提取到jsonArray

 public ArrayList<RequestModel> getData(String response)
        {
            Log.d("responseData :", response);
            ArrayList<RequestModel> dataList = new ArrayList<>();
            try {
                JSONObject mainObj = new JSONObject(response);
                JSONArray array = mainObj.getJSONArray("data");
                Log.d("The main Array :", array.toString());
                RequestModel data;
                for(int i = 0;i<array.length();i++)
                {
                    data = new RequestModel();
                    JSONObject resObj = array.getJSONObject(i);
                    JSONArray reqArray = resObj.getJSONArray("requests");
                    for( int j =0;j<reqArray.length();j++) {
                        JSONObject reqObj = reqArray.getJSONObject(j);
                        data.setAccessCode(reqObj.getString("accessCode"));
                        Log.d("Accessecode :", reqObj.getString("accessCode"));
                        data.setCustomerName(reqObj.getString("customerName"));
                        Log.d("customerName :", reqObj.getString("customerName"));
                    }

                    dataList.add(data);


                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            return dataList;
        }

Logcat正在打印JSONObject,但其显示为... data of type org.json.JSONObject cannot be converted to JSONArray

2 个答案:

答案 0 :(得分:1)

您正在尝试从data字段中提取数组,而响应包含一个对象。也许您打算获取对象data,然后从其中获取数组requests

答案 1 :(得分:0)

这可能是问题所在

JSONArray array = mainObj.getJSONArray("data");

数据是响应中看到的对象,而不是数组。