简体   繁体   English

如何使用Volley解析JSON?

[英]How to parse JSON using Volley?

i have some json output like this 我有一些像这样的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"
    }
}

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 但没有用,请多多帮助

You are not getting JSONArray anywhere, your response object has multiple JSONObject 您没有在任何地方获取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");
                    }

You can use some lib for Volley (eg VolleyEx ), together with Gson, to parse the JSON Object to a Map in Java. 您可以将Volley的某个库(例如VolleyEx )与Gson一起使用,以将JSON对象解析为Java中的Map。

ie using GsonObjectRequest instead of StringRequest 即使用GsonObjectRequest而不是StringRequest

developer.android.com has the code, but there are also libs doing that for you. developer.android.com有代码,但是也有库为您这样做。

example HERE 这里的例子

Use http://jsonviewer.stack.hu/ [To see json data structure] 使用http://jsonviewer.stack.hu/ [查看json数据结构]

  • braces {} its an JSONObject 大括号{}是一个JSONObject
  • brackets [] its an JSONArray 方括号[]是一个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(); } } 

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. 在这里,我只解析dataObject中的“ id”,“ userId”和“ shopId”。 Rest can be parse in similar way. 其余部分可以用类似的方式解析。

Before do it I will suggest you please read about the json Array and Json Object. 在此之前,我建议您先阅读有关JSON数组和Json对象的信息。 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. 在logcat中检查响应。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM