在volley中为jsonobject请求创建json

时间:2018-02-14 13:16:19

标签: android arrays json android-volley

我必须创建一个结构的json:

{
 "user_id":"1",
"program_id":"2",
"test_id":["1","2","3","4"],
"answers":["a","c","d","b"]
}

我无法传递字符串数组,当我传递字符串数组时,它就像: -

{
 "user_id":"1",
"program_id":"2",
"test_id":"[1,2,3,4]",
"answers":"[a,c,d,b]"
}

有人可以指导我如何使用上面所需的结构创建一个json吗?

2 个答案:

答案 0 :(得分:1)

我使用以下代码来实现它,ansArqAr是String arraylists:

JSONObject params = null;
        JSONArray jsonAns = new JSONArray(ansAr);
        JSONArray jsonQues = new JSONArray(qAr);
        try {
            params = new JSONObject();
            params.put("userId", mSessionManager.getToken());
            params.put("program_id", prgid); 
            params.put("test_id", jsonQues);
            params.put("answer", jsonAns);
            System.out.println("final params array" + params.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }

获取请求json如下:

{
 "user_id":"1",
"program_id":"2",
"test_id":["1","2","3","4"],
"answers":["a","c","d","b"]
}

答案 1 :(得分:0)

使用此..pattern创建json字符串数组..

String[] test_id = {"1", "2", "3", "4"};
JSONArray json = new JSONArray(Arrays.asList(data));