如何发送 json 数组作为 post 请求?

How to send json array as post request in volley?

我正在使用 volley 进行 json 解析。我想使用 POST 将一些数据发送到服务器端。我正在尝试发送。现在有人可以告诉我如何将过滤器数组发送到服务器吗?

以下是我的代码片段。我也尝试了 HashmapJsonobject。但出现此错误。

错误:

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

格式

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

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

代码检查贴

https://pastebin.com/u5qD8e2j

{
"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());

通过 JSONObject 进行请求。使用这个 https://www.androidhive.info/2014/09/android-json-parsing-using-volley/

如果您在调用 API 时遇到问题,那么这会对您有所帮助。

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

其中 jObject 是您要发送到服务器的 JSON 数据。

JSONArray 的实现类似。而不是 JsonObjectRequest 使用 JsonArrayRequest 并发送 jArray 而不是 jObject。

为了创建 json 数组只需做一点调整

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);
}

最后添加 json 数组如下

jsonParams.put("filter",array);

在您的情况下,您正在将 Json 数组转换为字符串

希望对您有所帮助。

    //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();
    }

有关如何创建 json 对象的更多信息,请查看此 link

Android JSONObject : add Array to the put method

编辑:

如果数据较多,最好使用 Gson 转换器

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

也用于创建 pojo 类 使用这个

http://www.jsonschema2pojo.org/

嗨 Volley 不支持 JsonArray 请求最好使用其他一些库...

我使用下面的代码 post JSONArray to volley。您必须使用 JsonArrayRequest 并直接传递 JSON 数组,而不将其添加到任何 JSON 对象。 还要记住重写 "parseNetworkResponse" 方法以再次将响应转换为 JSONArray,因为 JsonArrayRequest 的 ResponseListner 需要一种 JSONArray

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

以下三个步骤应该可以使其适用于缺少此支持的旧 Volley 库。

  1. 准备负载和post:

                        JSONArray payloadItems = new JSONArray();
    
                  JSONObject payloadItem1=new JSONObject();
                 //set properties on item1
                 payloadItem1.put('prop1',"val11");
    
                  payloadItems.put(payloadItem1);
    
                 JSONObject payloadItem2=new JSONObject();
                 //set properties on item1
                 payloadItem2.put('prop1',"val12");
    
                 payloadItems.put(payloadItem1);
    
    
                 JsonArrayRequest request;
    
                 request = new JsonArrayRequest(Request.Method.POST,url,payloadItems, new Response.Listener<JSONArray>() {
                    @SuppressWarnings("unchecked")
                    @Override
                    public void onResponse(JSONArray response) {
                        //your logic to handle response
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        //your logic to handle error
                    }
                }) {
    
                    public Map<String, String> getHeaders() throws AuthFailureError {
                        Map<String,String> params = new HashMap<String, String>();
                        /* This is very important to pass along */
                        params.put("Content-Type","application/json");
                        //other headers if any
                        return params;
                    }
    
                     };
    
    
    
    
                    request.setRetryPolicy(new DefaultRetryPolicy(10000, 2, 2));
                    VolleyHelper.init(this);
                    VolleyHelper.getRequestQueue().add(request);
    
  2. [如果需要] 在 Class- JsonArrayRequest 中添加此构造函数(如果还没有)

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

    }

  3. [如果需要] 如果尚未实现支持来自服务器的 JSONArray 响应,则覆盖此方法。

     @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));
     }