如何在android中解析JSONArray [英] how to parse JSONArray in android

查看:41
本文介绍了如何在android中解析JSONArray的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想阅读这个 JSON 行但是因为它以 JSONArray 开头我有点困惑

I want to read this JSON lines but because it start with JSONArray i'm a little confused

 "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).

i just need to use the "name" and save all as one String. (the string value will be : 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();
    }

推荐答案

如果您追求的是名称",为什么您的代码片段看起来像是试图获取字符"?

If you're after the 'name', why does your code snippet look like an attempt to get the 'characters'?

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

Anyways, this is no different from any other list- or array-like operation: you just need to iterate over the dataset and grab the information you're interested in. Retrieving all the names should look somewhat like this:

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);
}

(直接在浏览器中输入,所以没有测试).

(typed straight into the browser, so not tested).

这篇关于如何在android中解析JSONArray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆