簡體   English   中英

無法從jsonobject提取jsonarray

[英]Unable to extract jsonarray from jsonobject

我一直在與服務器使用改進的響應作斗爭。

我有來自服務器的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

您正在嘗試從data字段中提取數組,而響應包含一個對象。 也許您打算獲取對象data ,然后從其中requests數組。

這可能是問題所在:

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

數據是響應中看到的對象,而不是數組。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM