将ArrayList放入param JsonObject

时间:2015-04-21 17:40:40

标签: java android android-volley

我必须向Volley Framework请求。这是一个带有JSONObject的POST请求。

我必须传递一个字符串和一个JSONArray ..但我怎么做?

我从这开始:

 private String mUrl;
    private ArrayList<String> mUrlDove;

  HashMap<String, String> params = new HashMap<String, String>();
            params.put("url", mUrl);
            params.put("urlDove", mUrlDove); ---> Wrong because mUrlDove is not a String


            mUrl = app.getInstance().getmUrlRestWS() + getString(R.string.path);

            JsonObjectRequest mRequest = new JsonObjectRequest(
                    mUrl, new JSONObject(params),
                    createMyReqSuccessListener(),
                    createMyReqErrorListener()) {
                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    return app.getInstance().createBasicAuthHeader();
                }
            };

如果我尝试使用浏览器,我必须设置:

{
  "url": "www.secret.com",
  "urlDove" : [ "www.google.com","www.yahoo.com"]
}

2 个答案:

答案 0 :(得分:5)

尝试传递JSONObject而不是hashmap

JSONObject params = new JSONObject();
params.put("url", "www.secret.com");

JSONArray urlDove = new JSONArray();
urlDove.put("www.google.com");
urlDove.put("www.yahoo.com");

params.put("urlDove", urlDove);


JsonObjectRequest mRequest = new JsonObjectRequest(
                mUrl, params,
                createMyReqSuccessListener(),
                createMyReqErrorListener()) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                return app.getInstance().createBasicAuthHeader();
            }
        };

以供解析json https://stackoverflow.com/a/17810270/4810752

时的参考

答案 1 :(得分:4)

您需要先制作一个JSON数组然后存储

private String mUrl;
private ArrayList<String> mUrlDove;

HashMap<String, String> params = new HashMap<String, String>();
        params.put("url", mUrl);
        JSONArray jsArray = new JSONArray(mUrlDove);
        params.put("urlDove", jsArray.toString()); 

        mUrl = app.getInstance().getmUrlRestWS() + getString(R.string.path);

        JsonObjectRequest mRequest = new JsonObjectRequest(
                mUrl, new JSONObject(params),
                createMyReqSuccessListener(),
                createMyReqErrorListener()) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                return app.getInstance().createBasicAuthHeader();
            }
        };