【问题标题】:Problem with JSONArray response to android VolleyJSONArray 对 android Volley 响应的问题
【发布时间】:2019-08-28 08:38:05
【问题描述】:

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

[{"Nom_Carrera":"Cursa Popular 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 的位置,但它不起作用。如何解析数据以便将其保存在二维的普通数组中?

【问题讨论】:

    标签: php android arrays android-volley


    【解决方案1】:

    尝试使用JsonArrayRequest而不是JsonObjectRequest发送POST请求,因为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);
    

    【讨论】:

    • 它不起作用,错误如下: Error:(50, 45) error: reference to JsonArrayRequest is ambiguous both constructor JsonArrayRequest(int,String,JSONArray,Listener,ErrorListener ) 在 JsonArrayRequest 和构造函数 JsonArrayRequest(int,String,JSONObject,Listener,ErrorListener) 在 JsonArrayRequest 匹配
    • 您正面临该错误,因为您使用 JsonArrayRequest 发送一个 json 对象作为请求参数,它需要一个 json 数组对象作为 post 参数。因此,将 json 数组作为 post 参数与请求正文一起发送。它清楚地表明存在 JsonArrayRequest 构造函数参数不匹配。我已经用 volley 中 JsonArrayRequest 的正确请求参数序列更新了我的答案,请检查。可能您还需要修改您的 Web 服务以接受来自请求正文的 json 数组形式的参数。希望有帮助!!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多