-1

我有一个相当于的 json 数组

{
"genre":"2",
"imported_from":"1",
"release_year":"1999",
"import":"1",
"label":"1",
"artist":"Boards Of Canada ", 
"album_title":"Music Has The Right To Children",
"formats":"1"

}

我能够通过

JSONObject jsonObject = jsonArray.getJSONObject(i);

jsonObject.optString("genre");

但是我如何通过索引访问它尝试过 jsonObject.optInt(0); 但不起作用

4

2 回答 2

2

编辑:Android 没有提供可以使用索引的 API 的原因是因为在 JSON 规范中标签之间没有顺序,这意味着“流派”标签并不总是第一个元素(这实际上取决于 JSON解析器使用),所以以下是一个坏主意:

它不是那么有效,但它有效:

private int getInt(JSONObject jsonObject, int index) {
    int counter = 0;
    for(Iterator<String> i = jsonObject.keys(); i.hasNext(); ) {

        String item = i.next();

        if(counter == index){
            return jsonObject.optInt(item);
        }

        counter++;
    }

    return -1; //or default value/error
}
于 2013-10-29T09:58:10.230 回答
2

您只能在 Json 数组中通过 TAG_NAME 获取值,因为它是一个标签,而该标签值不是整个 Json 数组

{
"genre":"2",
"imported_from":"1",
"release_year":"1999",
"import":"1",
"label":"1",
"artist":"Boards Of Canada ", 
"album_title":"Music Has The Right To Children",
"formats":"1"
}
{
"genre":"2",
"imported_from":"1",
"release_year":"1999",
"import":"1",
"label":"1",
"artist":"Boards Of Canada ", 
"album_title":"Music Has The Right To Children",
"formats":"1"
}
{
"genre":"2",
"imported_from":"1",
"release_year":"1999",
"import":"1",
"label":"1",
"artist":"Boards Of Canada ", 
"album_title":"Music Has The Right To Children",
"formats":"1"
}

如果你是这样的人,那么从索引中你会得到第一个索引,它只是你得到的第一个数组(在两个 { } 所有标签和值之间)。

于 2013-10-29T09:47:47.753 回答