web-dev-qa-db-fra.com

Comment envoyer un tableau json sous forme de demande de poste en volley?

J'utilise volley pour l'analyse syntaxique. Je souhaite envoyer des données à l'aide de POST côté serveur. J'essaie d'envoyer. Maintenant, quelqu'un peut-il me dire que je peux envoyer un tableau de filtres au serveur? 

Voici mon code d'extrait. J'ai aussi essayé Hashmap et Jsonobject. mais obtenir cette erreur.

Erreur : 

org.json.JSONException: Value  at Data of type Java.lang.String cannot be converted to JSONObject

Format 

{
    "typeName": "MANUFACTURER",
    "typeId": 22,
    "cityId": 308,
    "sortBy": "productname",
    "sortOrder": "desc",
    "filter":[
                {
                    "filterId":101,
                    "typeName":"CAT_ID",

                     "filterId":102,
                    "typeName":"CAT_ID"
                }
             ]
}

Pour Code Check Pastie

https://Pastebin.com/u5qD8e2j

8
chris

Si vous rencontrez des problèmes lors de l'appel de l'API, cela vous aidera.

RequestQueue queue = Volley.newRequestQueue(this);
JsonObjectRequest jobReq = new JsonObjectRequest(Request.Method.POST, url, jObject,
        new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {

            }
        },
        new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        });

queue.add(jobReq);

où jObject correspond aux données JSON que vous souhaitez envoyer au serveur.

L'implémentation sera similaire pour JSONArray. Au lieu de JsonObjectRequest utilisez JsonArrayRequest et envoyez jArray au lieu de jObject.

Pour créer un tableau json, faites juste un petit tweak

JSONArray array=new JSONArray();

for(int i=0;i<filter_items.size();i++){
    JSONObject obj=new JSONObject();
    try {
        obj.put("filterId",filter_items.get(i));
        obj.put("typeName","CAT_ID");
    } catch (JSONException e) {
        e.printStackTrace();
    }
    array.put(obj);
}

Et enfin, ajoutez le tableau json comme ci-dessous

jsonParams.put("filter",array);

Dans votre cas, vous convertissez un tableau Json en chaîne 

8
Kunu

J'espère que cela vous aide.

    //Create Main jSon object
    JSONObject jsonParams = new JSONObject();

    try {
        //Add string params
        jsonParams.put("typeName", "MANUFACTURER");
        jsonParams.put("typeId", "22");
        jsonParams.put("cityId", "308");
        jsonParams.put("sortBy", "productname");
        jsonParams.put("sortOrder", "desc");
    } catch (JSONException e) {
        e.printStackTrace();
    }
    //Create json array for filter
    JSONArray array=new JSONArray();

    //Create json objects for two filter Ids
    JSONObject jsonParam1 =new JSONObject();
    JSONObject jsonParam2 =new JSONObject();

    try {

        jsonParam1.put("filterId","101");
        jsonParam1.put("typeName","CAT_ID");

        jsonParam2.put("filterId","102");
        jsonParam2.put("typeName","CAT_ID");
    } catch (JSONException e) {
        e.printStackTrace();
    }

    //Add the filter Id object to array
    array.put(jsonParam1);
    array.put(jsonParam2);

    //Add array to main json object
    try {
        jsonParams.put("filter",array);
    } catch (JSONException e) {
        e.printStackTrace();
    }

Pour plus d'informations sur la création d'objet JSON, cliquez sur ce lien.

Android JSONObject: ajouter un tableau à la méthode put

MODIFIER:

En cas de données supplémentaires, il est préférable d’utiliser le convertisseur Gson.

http://www.vogella.com/tutorials/JavaLibrary-Gson/article.html

Aussi pour créer des classes de pojo, utilisez cette

http://www.jsonschema2pojo.org/

2
Anonymous

Hi Volley ne supporte pas la requête JsonArray mais il vaut mieux utiliser d'autres librairies ...

2
Shanmugam
{
"typeName": "MANUFACTURER",
"typeId": 22,
"cityId": 308,
"sortBy": "productname",
"sortOrder": "desc",
"filter":[
            {
                "filterId":101,
                "typeName":"CAT_ID",
             }
             {
                 "filterId":102,
                "typeName":"CAT_ID"
            }
         ]
}


JSONObject object=new JSONObject();
object.put("typeName","");
object.put("typeId","");
object.put("cityId","");
object.put("sortBy","");
object.put("sortOrder","");
JSONArray array=new JSONArray();
JSONObject obj=new JSONObject();
obj.put("filterId","");
obj.put("typeName","");
array.put(obj);
object.put("filter",obj.toString());

passez JSONObject pour faire la demande. utilisez cette https://www.androidhive.info/2014/09/Android-json-parsing-using-volley/

2
Dheerubhai Bansal

J'ai utilisé le code ci-dessous pour poster JSONArray to volley. Vous devez utiliser JsonArrayRequest et transmettre directement le tableau JSON sans l'ajouter à aucun objet JSON . Gardez également à l'esprit de remplacer la méthode "parseNetworkResponse" pour convertir à nouveau la réponse en JSONArray en tant que ResponseListner pour JsonArrayRequest attend un type de JSON 

    String URL = "www.myposturl.com/data";

    RequestQueue queue = Volley.newRequestQueue(this);

    //Create json array for filter
    JSONArray array = new JSONArray();

    //Create json objects for two filter Ids
    JSONObject jsonParam = new JSONObject();
    JSONObject jsonParam1 = new JSONObject();

    try {
        //Add string params
        jsonParam.put("NAME", "XXXXXXXXXXXXXX");
        jsonParam.put("USERNAME", "XXXXXXXXXXXXXX");
        jsonParam.put("PASSWORD", "XXXXXXXXXXXX");
        jsonParam1.put("NAME", "XXXXXXXXXXXXXX");
        jsonParam1.put("USERNAME", "XXXXXXXXXXXXXX");
        jsonParam1.put("PASSWORD", "XXXXXXXXXXXX");
    } catch (JSONException e) {
        e.printStackTrace();
    }

    array.put(jsonParam);
    array.put(jsonParam1);
    JsonArrayRequest request_json = new JsonArrayRequest(Request.Method.POST, URL, array,
            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {
                    //Get Final response
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError volleyError) {
            VolleyLog.e("Error: ", volleyError.getMessage());

        }
    }) {
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            Map<String, String> headers = new HashMap<String, String>();
            // Add headers
            return headers;
        }
        //Important part to convert response to JSON Array Again
        @Override
        protected Response<JSONArray> parseNetworkResponse(NetworkResponse response) {
            String responseString;
            JSONArray array = new JSONArray();
            if (response != null) {

                try {
                    responseString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
                    JSONObject obj = new JSONObject(responseString);
                    (array).put(obj);
                } catch (Exception ex) {
                }
            }
            //return array;
            return Response.success(array, HttpHeaderParser.parseCacheHeaders(response));
        }
    };
    queue.add(request_json);
1
Neuron