小编典典

如何在Android中解析JSONArray

json

我想读这JSON行,但是因为它以JSONArray我开始有些困惑

 "abridged_cast": [
            {
                "name": "Jeff Bridges",
                "id": "162655890",
                "characters": [
                    "Jack Prescott"
                ]
            },
            {
                "name": "Charles Grodin",
                "id": "162662571",
                "characters": [
                    "Fred Wilson"
                ]
            },
            {
                "name": "Jessica Lange",
                "id": "162653068",
                "characters": [
                    "Dwan"
                ]
            },
            {
                "name": "John Randolph",
                "id": "162691889",
                "characters": [
                    "Capt. Ross"
                ]
            },
            {
                "name": "Rene Auberjonois",
                "id": "162718328",
                "characters": [
                    "Bagley"
                ]
            }
        ],

我只需要使用“名称”并将所有另存为一个字符串。(字符串值将是:Jeff Bridges,Charles Grodin,Jessica Lange,John
Randolph,Rene Auberjonois)。

这是我的代码:

try {
        //JSON is the JSON code above

        JSONObject jsonResponse = new JSONObject(JSON);
        JSONArray movies = jsonResponse.getJSONArray("characters");
        String hey = movies.toString();


    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

阅读 224

收藏
2020-07-27

共1个答案

小编典典

如果您使用的是“名称”,为什么您的代码片段看起来像是试图获取“字符”的尝试?

无论如何,这与任何其他类似于列表或数组的操作都没有什么不同:您只需要遍历数据集并获取您感兴趣的信息。检索所有名称应如下所示:

List<String> allNames = new ArrayList<String>();

JSONArray cast = jsonResponse.getJSONArray("abridged_cast");
for (int i=0; i<cast.length(); i++) {
    JSONObject actor = cast.getJSONObject(i);
    String name = actor.getString("name");
    allNames.add(name);
}

(直接输入浏览器,因此未经测试)。

2020-07-27