Android用json数组发送JsonObject

时间:2011-09-28 09:13:35

标签: android

我需要向服务器发送一个请求。 我需要发送的格式为:{“userId”:,“array”:(“A”,“b”,“c”,...)}

我可以发送jsonobject,但我不知道如何在一个请求中一起发送JsonObejct和Jsonarray。

3 个答案:

答案 0 :(得分:3)

我觉得这很容易吗?

JSONObject json = new JSONObject();
JSONArray array = new JSONArray();

for (String string : new String [] {"A", "b", "c", ...}) {
    array.put(string);
}

json.put("userId", theId);
json.put("array", array);
sendYourRequest(json);

// This is wrong! Code corrected. Thank you for the Feedback!!!
// json.put("array", new String [] {"A", "b", "c", ...});

答案 1 :(得分:1)

您需要创建JSONObject和JSONArrayObject。在json数组中添加所需的所有项目。然后将json数组添加到JsonObject中。见下文:

JSONArray array = new JSONArray();
array.put("1st array item");
array.put("2nd array item");

JSONObject holder = new JSONObject();       
holder.put("array", array);
holder.put("other_params", ...);

然后,您还可以通过执行以下操作验证json是否有效:

String jsonString = holder.toString(); //verify that the json is in the correct format

答案 2 :(得分:0)

这是一个很好的JSON Encoding Tutorial参考。