【问题标题】:Post Array as json in parameter using volly使用 volley 在参数中将数组作为 json 发布
【发布时间】:2019-01-10 05:02:03
【问题描述】:

问题是 API 没有被命中条件总是处于 else 条件。我无法获得有关成功的数据。我越来越对了 数组中的数据,但 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);
}
}

【问题讨论】:

  • 你指的是哪个IfElse?我可以看到 2 个不同的 if/else。另外,请发布字符串的结构
  • 有一个函数 add cart 在这个方法 api 被调用我没有得到 success_val "true",也许它正在返回其他条件 Log first log 在哪里

标签: android arrays json android-volley


【解决方案1】:

这两种方法将帮助您将 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;
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-07
    相关资源
    最近更新 更多