用于volley webService param的android传递数组

时间:2016-03-17 07:09:56

标签: android android-volley

我需要使用volley

将其作为我的Post param发送
{
    "userId": "xxx-xxx-xxx",
    "categories": ["Music"]
}

但在创建了身体参数之后,即时[获取实际的POST请求],

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

这是我的请求构建器

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;
    }
}

在这里我调用请求,

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>() { ...}

所以显然我正在构建错误的数组,如何正确解析这个数组的请求?

2 个答案:

答案 0 :(得分:2)

似乎类别(“类别”:[“音乐”])是一个JSONArray,所以你需要像 -

一样添加它
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;
    }

我希望现在能够奏效。

答案 1 :(得分:1)

试一试。

  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;
        }