简体   繁体   中英

Android - Java - Get nth element in JSONObject

My JSON file contains several attributes. One of them is a list of objects. I need to access this list via a numerical key, ie the 1st, the 2nd etc element.

When getting the nth element I want to access its attributes by a alphabetical key.

Example:

MyObj.get("itemlist").get(0).get("attribute")

If I do this I'm forced to convert the whole thing to an JSONArray from which (afaik) I can't access my attributes via a key but just by position.

Here's my JSON string:

{
"id": 1,
"items": [
    {
        "id": 1,
        "type": "video",
        "name": "test.mp4"
    },
    {
        "id": 2,
        "type": "image",
        "name": "pic.jpg"
    }
],
"name": "test"
}

Any ideas?

Ok, don't quite understand why but when I do the following it works:

JSONArray MyList = new JSONObject(filePath).getJSONArray("items");
System.out.println((((JSONObject) MyList.get(1)).get("type")));

So I just omitted the MyObj and targeted the list directly.

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