简体   繁体   中英

JSON - Create JSONObject with array

I need to create in a Java (Android) a JSONObject/JSONArray with the exact following structure:

{
    "listId": 
    [
        "c02bc683-fcd7-47a5-b157-853e26ed099e",
        "f8e1c9d7-ae45-4433-a315-726c1d912d09"
    ]
}

Can somebody help me on this please?

EDIT:

What i have is this:

JSONArray obj = new JSONArray();
JSONObject jsonObject = new JSONObject();

jsonObject.put("listId", folderId);
obj.put(jsonObject);

JSONObject json = new JSONObject();
json.put("id", obj);

But this produces something like:

{
    "listId": 
    [
        {"id":"c02bc683-fcd7-47a5-b157-853e26ed099e"},
        {"id":"f8e1c9d7-ae45-4433-a315-726c1d912d09"}
    ]
}

Thanks

You've got your array creation a bit mixed up. What you really want is an object holding an array of string, but what you're doing is creating an array of JSONObject .

Try this instead:

    String[] arr = { "c02bc683-fcd7-47a5-b157-853e26ed099e", "f8e1c9d7-ae45-4433-a315-726c1d912d09" };
    JSONArray jsonArray = new JSONArray(arr);

    JSONObject json = new JSONObject();
    json.put("listId", jsonArray);

    System.out.println(json); // {"listId":["c02bc683-fcd7-47a5-b157-853e26ed099e","f8e1c9d7-ae45-4433-a315-726c1d912d09"]}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM