1

I would like to create JSON format and I have some problem about this

I have no idea to create Jsonarray and JsonObject in JsonObject

{
   "users": [7, 16, 35],
   "group_id": "sdkfjsdkljflds"
}

I try

JSONObject jsonParams = new JSONObject();

try {
    jsonParams.put("group_id", "dlfsdds");
    jsonParams.put("users", list);

} catch (JSONException e) {
  e.printStackTrace();
}

and my log is show

{
   "users":"[7, 16, 35]",
   "group_id":"dlfsdds"
}

ps. list is from

for (int k=0;k<allMember.size();k++){
    list.add(allMember.get(k));
}

what is my mistake? and How to fix it?

thank for your help:D

1
  • You probably need to create a JSONArray from the list, and then add that. Otherwise the list will be converted to a string when it is added to the JSONObject. Commented Aug 12, 2017 at 6:26

1 Answer 1

2

You need to convert the list to JSONArray first:

try {
    jsonParams.put("group_id", "dlfsdds");

    JSONArray listJson = new JSONArray();

    for(int i=0; i<list.size(); i++) {
        listJson.put(list.get(i));
    }


    jsonParams.put("users", listJson);

} catch (JSONException e) {
  e.printStackTrace();
}

Most libraries also allow you to avoid the for-loop and simply do:

JSONArray listJson = new JSONArray(list);
Sign up to request clarification or add additional context in comments.

2 Comments

umm , sorry but it's not correct ,I want to set "users": [7, 16, 35] not "users":["7", "16", "35"]
@ARR.s It means that list is a List<String>. Change it to List<Integer>.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.