manuelBetancurt
manuelBetancurt

Reputation: 16138

android pass array for volley webService param

I need to send this as my Post param using volley

{
    "userId": "xxx-xxx-xxx",
    "categories": ["Music"]
}

but after creating the body params, im getting [on actual POST req],

{
    "userId": "xxx-xxx-xxx",
    "categories": "[Ljava.lang.String;@30f7436c"
}

This is my request builder,

public class RBGetLikesByCategory extends BaseRequestBuilder  {
    public static JSONObject getMyLikesForCategory(String[] categories)
    {
        JSONObject reqData = new JSONObject();
        try {
            reqData.put("userId", getLoginId());
            reqData.put("categories", categories.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return reqData;
    }
}

and here where I call the request,

RequestQueue rq = Volley.newRequestQueue(getActivity());
    String[] cats = {"Music"};
    JSONObject reqObject = RBGetLikesByCategory.getMyLikesForCategory(cats);

    MyAuthenticatedRequest jsObjRequest = new MyAuthenticatedRequest
            (Request.Method.POST, MyConstants.WebServiceEndPoints.MY_LIKES_URL, reqObject, new Response.Listener<JSONObject>() { ...}

So obviously im constructing the wrong Array, how to parse this array correctly for the request?

Upvotes: 0

Views: 613

Answers (2)

Govinda P
Govinda P

Reputation: 3319

Try It.

  public static JSONObject getCategory(String[] categories)
        {
            JSONObject request= new JSONObject();

            try {

       JSONArray jsonArray = new JSONArray(Arrays.asList(categories));  

                request.put("userId", getId());

            request.put("categories", categoryList);

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

Upvotes: 1

Vikram
Vikram

Reputation: 778

It seems categories("categories": ["Music"]) is a JSONArray so you need to add it like -

public static JSONObject getMyLikesForCategory(String[] categories)
    {
        JSONObject reqData = new JSONObject();
        JSONArray categoryList = new JSONArray();
        try {
            reqData.put("userId", getLoginId());

        //add all items in json array 
        for(int index = 0; index < categories.length; index++){
            categoryList.put(categories[index]);
        }

        reqData.put("categories", categoryList);

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

I hope now it will work.

Upvotes: 2

Related Questions