如何在Android的Volley中的Params中发送数组

时间:2018-12-12 10:59:03

标签: android android-studio android-layout android-fragments android-volley

我想使用凌空API将数据传递到服务器。参数如下:

Request:
{
    "user_id" : 6,
    "package_name": "Personal Package",
    "care_type" : ["help in shopping", "Personal care"],
    "care_delivered" : "as day care",
    "gender" : "F",
    "experience" : "4,0",
    "skills":"very helpful , caring, etc",
    "start_date" : "2018-09-12",
    "price": "200-700, day",
    "description": "test"
}

在此care_type中为数组类型。我已经完成了发送数据的代码,但是每次遇到错误

onErrorResponse: Error: org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject

我的API代码是:

 private void createPackageApi() {
    String tag_json_obj = "json_obj_req";
    String url = Constants.CREATE_PACKAGE;


    pBar.setVisibility(View.VISIBLE);
    Activity activity = getActivity();
    if (activity != null && isAdded()) {
        sessionManager = new SessionManager(activity);
    }


    final HashMap<String, String> packageDetail = sessionManager.getPackageDetail();
    JSONArray jsonArray;

    try {
        jsonArray = new JSONArray(required_support_need);
        strArr = new String[jsonArray.length()];

        Log.e("tag", "package" + required_support_need + " " + strArr);
        for (int i = 0; i < jsonArray.length(); i++) {
            strArr[i] = "\"" + jsonArray.getString(i) + "\"";
            Log.e("TAG", "getInitializedID:String " + strArr[i]);
        }


    } catch (Exception e) {

        e.printStackTrace();
    }


    final HashMap<String, String> registrationDetail = sessionManager.getSeekerRegistrationDetail();
    HashMap<String, String> params = new HashMap<String, String>();


    params.put("user_id", "2");
    params.put("package_name", edtPackageNames.getText().toString());
    params.put("care_type", Arrays.toString(strArr));
    params.put("care_delivered", edtCarePackages.getText().toString());
    params.put("gender", edtPreferredGender.getText().toString());
    params.put("experience", edtPackageNames.getText().toString());
    params.put("skills", edtEssentialSkills.getText().toString());
    params.put("start_date", packageDetail.get("start_date"));
    params.put("price", edtPackageValue.getText().toString());
    params.put("description", edtPackageDescription.getText().toString());


    Log.e("TAG", "seekerPackage: " + params);


    JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
            url, new JSONObject(params),
            new Response.Listener<JSONObject>() {

                @Override
                public void onResponse(JSONObject response) {

                    Log.e("package_detail_response", response.toString());

                    Gson gson = new Gson();
                    try {
                        if (response.has("success")) {

                            CreatePackage createPackage;
                            createPackage = gson.fromJson(response.toString(), CreatePackage.class);

                            String status = createPackage.getSuccess();

                            if (status.equals("success")) {
                                Activity activity = getActivity();
                                if (activity != null && isAdded()) {
                                    Toast.makeText(getActivity(), R.string.package_created, Toast.LENGTH_LONG).show();
                                }
                            }

                            pBar.setVisibility(View.GONE);

                        } else {


                            ResponseError responseError;
                            responseError = gson.fromJson(response.toString(), ResponseError.class);

                            String msg = responseError.getMessage();
                            Log.e("TAG", "msg " + msg);
                            Activity activity = getActivity();
                            if (activity != null && isAdded()) {
                                Toast.makeText(getActivity(), msg, Toast.LENGTH_LONG).show();
                            }
                        }


                    } catch (Exception e) {

                        e.printStackTrace();

                    }

                    pBar.setVisibility(View.GONE);
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            pBar.setVisibility(View.GONE);
            VolleyLog.e("Error: " + error.getMessage());
            // handle error
        }
    }) {

        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            HashMap<String, String> headers = new HashMap<String, String>();
            headers.put("Content-Type", "application/json; charset=UTF-8");
            headers.put("Authorization", "Bearer " + registrationDetail.get("api_token"));
            return headers;
        }
    };


    jsonObjReq.setRetryPolicy(new DefaultRetryPolicy(
            100000,
            DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));


    AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);
}

我尝试发送参数数组,但是没有成功。请告诉我如何在排球库中的单个参数中发送数组。

3 个答案:

答案 0 :(得分:1)

要发布数组,请使用以下代码

JSONArray care_type = new JSONArray();
for(int i=0; i < yourarray.length(); i++) {
    care_type.put(yourarray[i]);   // create array and add items into that 
}
params.put("care_type",care_type.toString());

答案 1 :(得分:1)

  

在JSONArray中添加数组,并使用键名将其发送到

JSONArray dataObject =新的JSONArray(filterListing);  paramObject.put(“ data”,dataObject);

答案 2 :(得分:0)

使用:

HashMap<String ,String> params=new HashMap<String, String>();
for(int i=1;i<=parms.size;i++){
   params.put("params_"+i, arr[i]);

}

使用JJSONArray发送Values。

 JSONArray jsonObject=new JSONArray();
 for(int i=1;i<=size;i++)
 {
    arr[i]="userId_"+i+"_"+"ans_"+i;
    jsonObject.put("params_"+i,arr[i]);
 }

HashMap<String ,String> params=new HashMap<String, String>();
params.put("params",jsonObject.toString());

要在服务器端发送所有值,请获取参数并转换为JSON对象并进行迭代以获取所有值