使用volly将数组作为json在参数中发布

时间:2018-08-02 12:12:57

标签: android arrays json android-volley

问题在于API未被命中的条件总是位于其他条件。我无法获得成功的数据。我说对了 数组中的数据,但API可能无法获取数组的字符串值 我正在遇到其他情况。
请帮我解决这个问题,我认为问题出在参数

{    JSONObject jo = new JSONObject();


            try {

                Collection<JSONObject> items = new ArrayList<JSONObject>();


                for (int i = 0; i < 1; i++) {

                    JSONObject item1 = new JSONObject();
                    item1.put("product_id", product_id);

                    if ("1".equals(getIntent().getStringExtra("catId"))) {
                        Log.d("Marked", "marked");
                        item1.put("quantity", String.valueOf(quant));
                        item1.put("cardId", String.valueOf(cardId));
                    } else {
                        item1.put("quantity", countText.getText().toString());
                        item1.put("cardId", String.valueOf(50));
                        Log.d("poker", "poker");
                    }
                    item1.put("price", money.getText().toString());
                    items.add(item1);
                }

                jo.put("cart_data", new JSONArray(items));

                Log.d("jsonmaidata", new JSONArray(items).toString());

                System.out.println(jo.toString());
            } catch (Exception e) {

                e.printStackTrace();


            }

            Log.d("checkJO", String.valueOf(jo));

            Log.d("mobile", session.getUserDetails().get(SessionManagement.KEY_MOBILE));

            add_cart(String.valueOf(jo), new CallBack() {

                @Override
                public void onSuccess(String data) {

                    Log.d("loginnnnninnnter", data);
                    try {
                        JSONObject obj = new JSONObject(data);
                        String success_val = obj.getString("success");

                        if ("true".equals(success_val)) {
                            DatabaseHandler db = new DatabaseHandler(getApplicationContext());
                            Boolean result = db.insert_for_go_to_cart(product_id);

                            //   Log.d("hjffhui", String.valueOf(result));

                            Toast.makeText(product_details.this, " added in cart", Toast.LENGTH_SHORT).show();
                            add_to_cart.setText("GO TO CART");


                            onResume();

                            AppRater.showRateDialog(product_details.this);


                            // AppRater.app_launched(product_details.this);

                  /*   Intent i=new Intent(getApplicationContext(), com.active_india.Fragment.add_to_cart.class);
                     startActivity(i);*/

                        } else {

                            Log.d("firstLog", "firstwala");
                            Intent i = new Intent(getApplicationContext(), com.kk_cards.Fragment.add_to_cart.class);
                            i.putExtra("test", "");
                            startActivity(i);
                            Toast.makeText(product_details.this, "Item already exist in cart", Toast.LENGTH_SHORT).show();


                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }


                    Log.d("jhvfff", data);


                    //    Toast.makeText(getActivity(), ""+data, Toast.LENGTH_SHORT).show();

                }

                @Override
                public void onFail(String msg) {

                    Toast.makeText(product_details.this, "Invalid Login Details", Toast.LENGTH_SHORT).show();
                    Log.d("jhvfff", "failed");
                    // Do Stuff
                }
            });

        } else {

            Intent i = new Intent(getApplicationContext(), com.kk_cards.Fragment.add_to_cart.class);

            Log.d("secondLog", "Secondwala");
            i.putExtra("test", "");
            startActivity(i);


        }


private void add_cart(final String cart_data, final CallBack onCallBack) {


    StringRequest stringRequest = new StringRequest(Request.Method.POST, Config.Base_Url + "/API/cartApi.php",
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    onCallBack.onSuccess(response);
                    Log.d("derailss", response);


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


                }
            }) {
        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<String, String>();
            params.put("cart", cart_data);
            params.put("mobile", session.getUserDetails().get(SessionManagement.KEY_MOBILE));


            return params;
        }

        private Map<String, String> checkParams(Map<String, String> map) {
            Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry<String, String> pairs = (Map.Entry<String, String>) it.next();
                if (pairs.getValue() == null) {
                    map.put(pairs.getKey(), "");
                }
            }
            return map;
        }


        @Override
        protected Response<String> parseNetworkResponse(NetworkResponse response) {
            if (response.headers == null) {
                // cant just set a new empty map because the member is final.
                response = new NetworkResponse(
                        response.statusCode,
                        response.data,
                        Collections.<String, String>emptyMap(), // this is the important line, set an empty but non-null map.
                        response.notModified,
                        response.networkTimeMs);


            }

            return super.parseNetworkResponse(response);
        }
    };


    RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
    requestQueue.add(stringRequest);
}
}

1 个答案:

答案 0 :(得分:0)

这2种方法将帮助您将jsonarray转换为String并将字符串转换回jsonArray

    public static String jsonArrToString(JsonArray arr) {
        Gson gson = new Gson();
        Type type = new TypeToken<JsonArray>() {
        }.getType();
        String json = gson.toJson(arr, type);
        return json;
    }

    public static String[] stringToJsonArray(String json) {
        Gson gson = new Gson();
        Type type = new TypeToken<String[]>() {
        }.getType();
        JsonArray arr = gson.fromJson(json, type);
        return arr;
    }