Android 如何使用截取解析JSON?

Android 如何使用截取解析JSON?,android,json,android-volley,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", "

我有一些类似这样的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);
StringRequest request=newstringrequest(request.Method.POST,ApiService.ORDER\u电池,new Response.Listener()){
@凌驾
公共void onResponse(字符串响应){
试一试{
BookBattery BookBattery=新的BookBattery();
JSONObject JSONObject=新JSONObject(响应);
如果(!jsonObject.has(“success”)){
JSONObject object=JSONObject.getJSONObject(“电池”);
字符串数据=object.getString(“”);
JSONArray JSONArray=jsonObject.getJSONArray(“数据”);
}否则{
Log.e(“您的数组响应”,“数据为空”);
}
}捕获(JSONException e){
e、 printStackTrace();
}
}
},new Response.ErrorListener(){
@凌驾
公共无效onErrorResponse(截击错误){
Log.e(“错误为“,”+错误);
}
}) {
//如果需要,这是用于标题的
@凌驾
公共映射getHeaders()引发AuthFailureError{
Map params=新的HashMap();
参数put(“内容类型”,“应用程序/json;字符集=UTF-8”);
参数put(“令牌”,令牌用户);
返回参数;
}
//在这里传递您的参数
@凌驾
受保护的映射getParams(){
Map params=新的HashMap();
参数put(“shopId”,String.valueOf(shopId));
//参数put(“通过”,密码);
返回参数;
}
};
AppController.getInstance().addToRequestQueue(请求,标记为json\u obj);

但是不起作用,请帮助,非常感谢

您没有得到
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");
                    }

在此之前,我建议您阅读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);
HashMap params=newhashmap();
put(“您的json参数名”,json参数值);
//参数put(“设备id”,设备id);
Log.d(“response11”,String.valueOf(params));
String Url=“您的服务器Url”;
JsonObjectRequest JsonObjectRequest=新的JsonObjectRequest(Request.Method.POST,Url,
新建JSONObject(params),新建Response.Listener(){
@凌驾
公共void onResponse(JSONObject响应){
Log.d(TAG+“JO”,String.valueOf(response));
试一试{
字符串msgObject=response.getString(“消息”);
Log.d(“响应”、“msgObject”);
}捕获(JSONException e){
字符串jsonExp=e.getMessage();
Log.d(TAG+“JE”,jsonExp);
}
}
},new Response.ErrorListener(){
@凌驾
公共无效onErrorResponse(截击错误){
字符串volleyErr=error.getMessage();
对数d(标记+V”,截击);
}
});
add(jsonObjectRequest);

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

您可以使用一些用于截取的库(例如),与Gson一起,将JSON对象解析为Java中的映射

i、 e.使用
GsonObjectRequest
代替
StringRequest

有代码,但也有lib为您做这件事

示例

使用[查看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();
     }
     }
    
试试这个

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);
StringRequest request=newstringrequest(request.Method.POST,ApiService.ORDER\u电池,new Response.Listener()){
@凌驾
公共void onResponse(字符串响应){
试一试{
BookBattery BookBattery=新的BookBattery();
JSONObject JSONObject=新JSONObject(响应);
String message=jsonObject.getString(“消息”);
if(message.equalsIgnoreCase(“成功”)){
字符串电池=jsonObject.getString(“电池”);
JSONObject dataObject=JSONObject.getJSONObject(“数据”);
JSONObject shopDataObject=JSONObject.getJSONObject(“shopData”);
int dataId=dataObject.getInt(“id”);
int dataUserId=dataObject.getInt(“userId”);
int dataShopId=dataObject.getInt(“shopId”);
}否则{
Log.e(“您的数组响应”,“数据为空”);
}
}捕获(JSONException e){
e、 printStackTrace();
}
}
},new Response.ErrorListener(){
@凌驾
公共无效onErrorResponse(截击错误){
Log.e(“错误为“,”+错误);
}
}) {
//如果需要,这是用于标题的
@凌驾
公共映射getHeaders()引发AuthFailureError{
Map params=新的HashMap();
参数put(“内容类型”,“应用程序/json;字符集=UTF-8”);
参数put(“令牌”,令牌用户);
返回参数;
}
//在这里传递您的参数
@凌驾
受保护的映射getParams(){
Map params=新的HashMap();
帕玛斯·普蒂