如何使用Volley解析JSON?

时间:2019-01-04 09:09:41

标签: android json android-volley

我有一些像这样的json输出

{
    "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"
    }
}

我像这样用凌空抽空实现

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);

但无法正常工作,请多多帮助

5 个答案:

答案 0 :(得分:0)

您无处获得JSONArray,您的响应对象有多个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");
                    }

答案 1 :(得分:0)

您可以将Volley的某个库(例如VolleyEx)与Gson一起使用,以将JSON对象解析为Java中的Map。

即使用GsonObjectRequest代替StringRequest

developer.android.com有代码,但是也有库为您这样做。

示例HERE

答案 2 :(得分:0)

使用http://jsonviewer.stack.hu/ [查看json数据结构]

  • 括号 {} 是一个JSONObject
  • 括号 [] 是一个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();
     }
     }
    

答案 3 :(得分:0)

尝试一下

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);

在这里,我仅解析dataObject中的“ id”,“ userId”和“ shopId”。其余部分可以用类似的方式解析。

答案 4 :(得分:-1)

在此之前,我建议您阅读有关JSON数组和Json对象的信息。 解决方法在这里。

 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);

这足以打印您的服务器响应。在logcat中检查响应。