在 Volley 中获取 json 响应

Rah*_*hul 1 android json android-volley

我有以下 json 响应

{"multicast_id":8XXXD,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:14XX"}]}
Run Code Online (Sandbox Code Playgroud)

我想检查 java 中是否failure = 0。以下是我的排球代码。

StringRequest stringRequest = new StringRequest(Request.Method.POST, CONN_URL.send_single_push,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Toast.makeText(getActivity(), response, Toast.LENGTH_LONG).show();
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            }) {
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            Map<String, String> params = new HashMap<>();
            params.put("title", title);
            params.put("message", message);

            if (!TextUtils.isEmpty(image))
                params.put("image", image);

            params.put("course", course);
            return params;
        }
    };

    MySingleton.getInstance(getActivity()).addToRequestQueue(stringRequest);
Run Code Online (Sandbox Code Playgroud)

我是安卓新手。请帮我解决这个问题。

Ahm*_*yaz 5

你可以通过这样做来做到这一点。

首先,您需要将 String 响应转换为 JSON 响应

StringRequest stringRequest = new StringRequest(Request.Method.POST, CONN_URL.send_single_push,
        new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                JSONObject obj = new JSONObject(response);
                int failure = obj.optInt("failure");
                if (failure == 0){
                }else{  
                }
            }
        },
        new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        }) {
    @Override
    protected Map<String, String> getParams() throws AuthFailureError {
        Map<String, String> params = new HashMap<>();
        params.put("title", title);
        params.put("message", message);

        if (!TextUtils.isEmpty(image))
            params.put("image", image);

        params.put("course", course);
        return params;
    }
};
Run Code Online (Sandbox Code Playgroud)