简体   繁体   English

如何在Android中解析JSONArray

[英]how to parse JSONArray in android

I want to read this JSON lines but because it start with JSONArray i'm a little confused 我想阅读此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"
                ]
            }
        ],

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). (字符串值将是:Jeff Bridges,Charles Grodin,Jessica Lange,John Randolph,Rene Auberjonois)。

this is my code: 这是我的代码:

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). (直接输入浏览器,因此未经测试)。

getJSONArray(attrname) will get you an array from the object of that given attribute name in your case what is happening is that for 在您的情况下,getJSONArray(attrname)将从给定属性名称的对象获取一个数组,这是针对

{"abridged_cast":["name": blah...]}
^ its trying to search for a value "characters"

but you need to get into the array and then do a search for "characters" 但您需要进入数组,然后搜索“字符”

try this 尝试这个

String json="{'abridged_cast':[{'name':'JeffBridges','id':'162655890','characters':['JackPrescott']},{'name':'CharlesGrodin','id':'162662571','characters':['FredWilson']},{'name':'JessicaLange','id':'162653068','characters':['Dwan']},{'name':'JohnRandolph','id':'162691889','characters':['Capt.Ross']},{'name':'ReneAuberjonois','id':'162718328','characters':['Bagley']}]}";

    JSONObject jsonResponse;
    try {
        ArrayList<String> temp = new ArrayList<String>();
        jsonResponse = new JSONObject(json);
        JSONArray movies = jsonResponse.getJSONArray("abridged_cast");
        for(int i=0;i<movies.length();i++){
            JSONObject movie = movies.getJSONObject(i);
            JSONArray characters = movie.getJSONArray("characters");
            for(int j=0;j<characters.length();j++){
                temp.add(characters.getString(j));
            }
        }
        Toast.makeText(this, "Json: "+temp, Toast.LENGTH_LONG).show();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

checked it :) 检查了它 :)

Here is a better way for doing it. 这是一种更好的方法。 Hope this helps 希望这可以帮助

protected void onPostExecute(String result) {
                Log.v(TAG + " result);


                if (!result.equals("")) {

                    // Set up variables for API Call
                    ArrayList<String> list = new ArrayList<String>();

                    try {
                        JSONArray jsonArray = new JSONArray(result);

                        for (int i = 0; i < jsonArray.length(); i++) {

                            list.add(jsonArray.get(i).toString());

                        }//end for
                    } catch (JSONException e) {
                        Log.e(TAG, "onPostExecute > Try > JSONException => " + e);
                        e.printStackTrace();
                    }


                    adapter = new ArrayAdapter<String>(ListViewData.this, android.R.layout.simple_list_item_1, android.R.id.text1, list);
                    listView.setAdapter(adapter);
                    listView.setOnItemClickListener(new OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                            // ListView Clicked item index
                            int itemPosition = position;

                            // ListView Clicked item value
                            String itemValue = (String) listView.getItemAtPosition(position);

                            // Show Alert
                            Toast.makeText( ListViewData.this, "Position :" + itemPosition + "  ListItem : " + itemValue, Toast.LENGTH_LONG).show();
                        }
                    });

                    adapter.notifyDataSetChanged();
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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