How to parse JSON using Volley?

2019-08-27 15:32发布

i have some json output like this

{
    "message": "success",
    "battery": "AHAJAJ1DH13T0021",
    "data": {
        "id": 6,
        "userId": 3,
        "shopId": 1,
        "transactionStatus": "PENDING",
        "expiredAt": "2019-01-04T03:01:18.878Z",
        "updatedAt": "2019-01-04T02:01:18.916Z",
        "createdAt": "2019-01-04T02:01:18.916Z",
        "paymentId": null,
        "batteryNo": null
    },
    "shopData": {
        "id": 1,
        "name": "test1",
        "tel": "555",
        "address": "cikarang",
        "description": "showroom",
        "latitude": "-6.307923199999999",
        "longitude": "107.17208499999992",
        "open_time": "10.00",
        "battery_available": 16,
        "battery_booked": 1,
        "status": 1,
        "createdAt": "2018-12-28T03:59:55.156Z",
        "updatedAt": "2019-01-04T02:01:18.940Z"
    }
}

and i implement using volley like this

StringRequest request = new StringRequest(Request.Method.POST, ApiService.ORDER_BATTERY, new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try{
                            BookBattery bookBattery = new BookBattery();
                            JSONObject jsonObject = new JSONObject(response);
                        if (!jsonObject.has("success")) {
                            JSONObject object = jsonObject.getJSONObject("battery");
                            String data =  object.getString("");
                            JSONArray jsonArray = jsonObject.getJSONArray("data");




                        } else {
                            Log.e("Your Array Response", "Data Null");
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.e("error is ", "" + error);
                    }
                }) {

                    //This is for Headers If You Needed
                    @Override
                    public Map<String, String> getHeaders() throws AuthFailureError {
                        Map<String, String> params = new HashMap<String, String>();
                        params.put("Content-Type", "application/json; charset=UTF-8");
                        params.put("token", TokenUser);
                        return params;
                    }

                    //Pass Your Parameters here
                    @Override
                    protected Map<String, String> getParams() {
                        Map<String, String> params = new HashMap<String, String>();
                        params.put("shopId", String.valueOf(shopId));
                        //params.put("Pass", PassWord);
                        return params;
                    }
                };

                AppController.getInstance().addToRequestQueue(request, tag_json_obj);

but not working, please help thanks a lot

5条回答
来,给爷笑一个
2楼-- · 2019-08-27 15:49

Before do it I will suggest you please read about the json Array and Json Object. Here the solution.

 HashMap<String, String> params = new HashMap<String, String>();
        params.put("your json parameter name", json parameter value);
//        params.put("device_id", deviceID);
        Log.d("response11", String.valueOf(params));

        String Url ="your server url";


JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, Url,
            new JSONObject(params), new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            Log.d(TAG + "JO", String.valueOf(response));

            try {
                String msgObject = response.getString("message");
                Log.d("response","msgObject");


            }catch (JSONException e){
                String jsonExp = e.getMessage();
                Log.d(TAG + "JE", jsonExp);
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            String volleyErr = error.getMessage();
            Log.d(TAG + "VE", volleyErr);
        }
    });
    requestQueue.add(jsonObjectRequest);

this sufficient for print you server response. check response in logcat.

查看更多
祖国的老花朵
3楼-- · 2019-08-27 15:56

You can use some lib for Volley (e.g. VolleyEx), together with Gson, to parse the JSON Object to a Map in Java.

i.e. using GsonObjectRequest instead of StringRequest

developer.android.com has the code, but there are also libs doing that for you.

example HERE

查看更多
SAY GOODBYE
4楼-- · 2019-08-27 16:00

You are not getting JSONArray anywhere, your response object has multiple JSONObject

JSONObject jsonObject = new JSONObject(response);

                    if (!jsonObject.has("success")) {
                        JSONObject object = jsonObject.getJSONObject("battery");

                        JSONOnject jsonObject2= jsonObject .getJSONObject("data");// here you need to change.

                        String batteryNo=jsonObject2.getJSONObject("batteryNo");


                        JSONOnject jsonObject3= jsonObject1.getJSONObject("shopData");
                        String address=jsonObject2.getJSONObject("address");



                    } else {
                        Log.e("Your Array Response", "Data Null");
                    }
查看更多
迷人小祖宗
5楼-- · 2019-08-27 16:04

Use http://jsonviewer.stack.hu/ [To see json data structure]

  • braces {} its an JSONObject
  • brackets [] its an JSONArray

     public void parseJson() {
     try {
     JSONObject jsonObject = new JSONObject(jsonParsing);
     boolean isSuccess = jsonObject.getString("message").contains("success");
     if (isSuccess) {
    
     JSONObject jsonObjectData = jsonObject.getJSONObject("data");
     String userId = jsonObject.getString("userId");
    
     JSONObject jsonObjectShopData = jsonObject.getJSONObject("shopData");
     String name = jsonObject.getString("tel");
    
     }
     } catch (JSONException e) {
     e.printStackTrace();
     }
     }
    
查看更多
Ridiculous、
6楼-- · 2019-08-27 16:05

Try this

StringRequest request = new StringRequest(Request.Method.POST, ApiService.ORDER_BATTERY, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try{
                    BookBattery bookBattery = new BookBattery();
                    JSONObject jsonObject = new JSONObject(response);
                    String message = jsonObject.getString("message");
                    if (message.equalsIgnoreCase("success")) {
                        String battery = jsonObject.getString("battery");
                        JSONObject dataObject = jsonObject.getJSONObject("data");
                        JSONObject shopDataObject = jsonObject.getJSONObject("shopData");
                        int dataId = dataObject.getInt("id");
                        int dataUserId = dataObject.getInt("userId");
                        int dataShopId = dataObject.getInt("shopId");
                    } else {
                        Log.e("Your Array Response", "Data Null");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("error is ", "" + error);
            }
        }) {

            //This is for Headers If You Needed
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> params = new HashMap<String, String>();
                params.put("Content-Type", "application/json; charset=UTF-8");
                params.put("token", TokenUser);
                return params;
            }

            //Pass Your Parameters here
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                params.put("shopId", String.valueOf(shopId));
                //params.put("Pass", PassWord);
                return params;
            }
        };

        AppController.getInstance().addToRequestQueue(request, tag_json_obj);

here i only parse "id", "userId" & "shopId" from dataObject. Rest can be parse in similar way.

查看更多
登录 后发表回答