13

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

以下是我的代码段。Hashmap我也试过了Jsonobject。但得到这个错误。

错误 :

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

4

6 回答 6

14

如果您在调用 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 数组转换为字符串

于 2017-09-26T09:45:25.047 回答
6

我使用下面的代码将 JSONArray 发布到凌空。您必须使用 JsonArrayRequest 并直接传递 JSON 数组而不将其添加到任何 JSONObject。还要记住重写“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);
于 2018-06-15T10:25:41.270 回答
2

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

于 2017-10-05T09:12:08.783 回答
2
{
"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/

于 2017-09-26T09:38:46.123 回答
2

希望这可以帮助你。

    //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 对象的更多信息,请查看此链接

Android JSONObject:将数组添加到 put 方法

编辑

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

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

也用于创建 pojo 类使用这个

http://www.jsonschema2pojo.org/

于 2017-09-28T11:20:58.957 回答
0

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

  1. 准备有效载荷并发布:

                        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. [如果需要] 在 Volley 包中的 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));
     }
    
于 2020-01-13T09:27:14.533 回答