JSONArray对Android Volley的响应问题

时间:2019-04-06 18:47:55

标签: php android arrays android-volley

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

[{“ Nom_Carrera”:“库尔萨流行BCN”,“ Ciudad”:“巴塞罗那”,“ Anyo”:“ 2019”},{“ Nom_Carrera”:“ Maraton Madrid”,“ Ciudad”:“马德里”, “ Anyo”:“ 2018”},{“ Nom_Carrera”:“ Mitja Marato Valencia”,“ Ciudad”:“ Valencia”,“ Anyo”:“ 2018”}]

我知道这是一个JSONArray,但是如何在凌空方法中解析此数据?

我的android代码如下:

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的位置,但是它不起作用。如何解析数据以使其具有二维的常规数组?

1 个答案:

答案 0 :(得分:2)

由于API响应是一个JSON数组,请尝试使用JsonArrayRequest而不是JsonObjectRequest发送POST请求

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