首页 > 解决方案 > JSONArray 对 android Volley 响应的问题

问题描述

我正在将此数据从 php 文件发送到 android:

[{"Nom_Carrera":"Cursa 流行 BCN","Ciudad":"Barcelona","Anyo":"2019"},{"Nom_Carrera":"Maraton Madrid","Ciudad":"马德里","Anyo" :"2018"},{"Nom_Carrera":"Mitja Marato Valencia","Ciudad":"Valencia","Anyo":"2018"}]

我知道这是一个 JSONArray,但是如何用 volley 方法解析这些数据?

我的安卓代码如下:

public void cargarcarreras(String usuario){
        queue = Volley.newRequestQueue(this);

        // Los parametros para el php, hacemos el mapping para poder pasarlo a JSON
        // map.put(KEY, VALUE);
        map.put("uname", usuario);

        // La solicitud JSON
        // JsonObjectRequest(METHOD, URL, JSONOBJECT(PARAMETERS), OK_LISTENER, ERROR_LISTENER);

        request = new JsonObjectRequest(
                Request.Method.POST, // the request method
                "http://192.168.1.41:8080/Consulta_Carreras_UnVoluntarioEspecifico_APP.php", // the URL
                new JSONObject(map), // the parameters for the php
                new Response.Listener<JSONObject>() { // the response listener
                    @Override
                    public void onResponse(JSONObject response){
                        // Aquí parseamos la respuesta
                        Log.d("Response", String.valueOf(response));
                        // Aquí parseamos la respuesta

                        JSONObject myJson = response;

                        String resp = null;
                        try { //Comprovamos la respuesta recivida del server
                            resp = myJson.getString("res");
                            if(resp.equals("OK")){//Se ha inciado sesion corectamente
                                //lertmessageLogin(1);
                                //openUserMenu();// Abrimos la activity del menu
                            }
                            if(resp.equals("KO")){//La contrseña que se ha dado es incorrecta
                                //alertmessageLogin(2);

                            }
                            if(resp.equals("KO2")){//El usuario que se ha dado no existe

                                //alertmessageLogin(0);

                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                },
                new Response.ErrorListener() { // the error listener
                    @Override
                    public void onErrorResponse(VolleyError error) { // En caso de error con la conexon con el server entrariamos en esta parte del codigo

                        //alertmessageLogin(4);
                        String vvv="kjdjfbg";

                    }
                });

        // Ejecutamos la solicitud para btener la informcion en formato JSON
        queue.add(request);



    }

我尝试将 JsonArray 放在放置响应 JSONobject 的位置,但它不起作用。如何解析数据以便将其保存在正常的二维数组中?

标签: phpandroidarraysandroid-volley

解决方案


尝试使用JsonArrayRequest而不是发送 POST 请求JsonObjectRequest,因为 API 响应是 JSON 数组

 /**
 * Parameters expected for a JsonArrayRequest
 *
 * @param method the HTTP method to use
 * @param url URL to fetch the JSON from
 * @param jsonRequest A {@link JSONArray} to post with the request. Null indicates no parameters
 *     will be posted along with request.
 * @param listener Listener to receive the JSON response
 * @param errorListener Error listener, or null to ignore errors.
*/

public JsonArrayRequest(
        int method,
        String url,
        @Nullable JSONArray jsonRequest,
        Response.Listener<JSONArray> listener,
        @Nullable Response.ErrorListener errorListener) {
    super(
            method,
            url,
            (jsonRequest == null) ? null : jsonRequest.toString(),
            listener,
            errorListener);
}


// Example to make a JsonArrayRequest

// Initialize a new RequestQueue instance
            RequestQueue requestQueue = Volley.newRequestQueue(mContext);

            // Initialize a new JsonArrayRequest instance
            JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(
                    Request.Method.POST,
                    "http://192.168.1.41:8080/Consulta_Carreras_UnVoluntarioEspecifico_APP.php", // the URL
                    null,
                    new Response.Listener<JSONArray>() {
                        @Override
                        public void onResponse(JSONArray response) {

                            // Process the JSON
                            try{
                                // Loop through the array elements
                                for(int i=0;i<response.length();i++){
                                    // Get the individual json object
                                    JSONObject jsonObject = response.getJSONObject(i);

                                                                        }
                            }catch (JSONException e){
                                e.printStackTrace();
                            }
                        }
                    },
                    new Response.ErrorListener(){
                        @Override
                        public void onErrorResponse(VolleyError error){
                            // Do something when error occurred
                                                      }
                    }
            );

            // Add JsonArrayRequest to the RequestQueue
            requestQueue.add(jsonArrayRequest);

推荐阅读