如何将String []数组放入Volley的JsonObject Post Request中

时间:2018-04-05 09:49:55

标签: android json android-volley

我正在使用Volley将数据发布到Api.I需要发布Json对象.Json对象由一个String数组组成。JSON请求的POST对象的格式是

{
"id":"00001",
"roles":["1", "2", "4"],
"notes":"special"
}  

我的字符串[]采用String roles[]=["11", "3"]的形式 我的Json Post Request是

private void assign() {
        String url = "";
        JSONObject object = new JSONObject();
        try {
            object.put("id",id);
            object.put("roles",roles);
            object.put("no_people",people);
            object.put("notes","special");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, object, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        })  

我在发布角色对象时收到错误代码400.如何为帖子请求构建此对象?

2 个答案:

答案 0 :(得分:0)

以下是我要为JSON添加数组的方法:

为您的角色数组创建一个JSONArray,它将放在您的主JSONObject中。 然后,您必须迭代角色的数组,在将新元素添加到JSONObject之前将每个元素添加到新创建的JSONArray中:

JSONArray tmp = new JSONArray();
for (i=0, i<roles.length, i++)
  tmp.put(roles[i]);
object.put("roles", tmp);

不确定它是否真的是你要求的,我觉得你的帖子和它的标题并没有要求同样的事情。

答案 1 :(得分:0)

Map<String, String> params = new HashMap<String, String>();
params.put("tag", "test");

JSONObject jsonObj = new JSONObject(params);

添加像这样的参数