java 如何在android中解析单个对象中的嵌套json数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14933173/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 17:54:48  来源:igfitidea点击:

How to parse nested json arrays in a single object in android

javaandroidjson

提问by Reyjohn

I have a json which has a number of nested JSONARRAY. here is the snippet.

我有一个 json,它有许多嵌套的 JSONARRAY。这是片段。

{
    "location": [ 
        { 
            "name": "Perth", 
            "conferencelocation": [
                {
                    "locationname":"Stage 1" ,
                    "guests": [
                        {
                            "guestid":"4074513426041094",
                            "guestname":"Keegan Connor Tracy",
                            "time":"9am",
                            "largeimg":"http://ozcomiccon.com/images/banner/Keegan.jpg",
                            "smallimg":"http://ozcomiccon.com/images/banner/Keeganresized.jpg",
                            "biotext": "Born in Windsor, Ontario, Canada, Tracy attended Wilfrid Laurier University in Waterloo, Ontario, Canada, where she orginally studied business. She later switched to psychology. She spent a year in Europe working in Dublin, Paris and Nice, where she was supposed to be completing her 4th year of study. She later returned to WLU to finish her degree. She moved to Vancouver, B.C. where she has had all of her acting jobs.",
                            "autographs":" each (an 8x10 photograph will be included with each signature, or you may choose to have an appropriate personal item signed).",
                            "photographs":"Photo with Keegan .",
                            "genre":"acting",
                            "links": [
                                {"linkname":"Twitter", "url":"https://twitter.com/keegolicious" },
                                {"linkname":"IMDB", "url":"http://www.imdb.com/name/nm0870535/" }
                            ]
                        },
                        {
                            "guestid":"1054713366041913",
                            "guestname":"Matthew Clark",
                            "time":"10am",
                            "largeimg":"http://ozcomiccon.com/images/banner/matthewclark.jpg",
                            "smallimg":"http://ozcomiccon.com/images/banner/matthewclarkresized.jpg",
                            "biotext": "Matthew Clark is a comic book artist living and working in Portland, Oregon. Having worked on art of some of the most well-known DC characters in comic book history, he  recently did pencils for DCa?s latest version of the Doom Patrol. Matthew is currently working on Ghost Rider for Marvel Comics, with whom he has signed an exclusive two-year deal.<br /><br />Matthew has lived in Portland for the past 13 years, just above an art gallery in the heart of downtown. He loves to walk around this fair city (mainly because he sold his car and needed to force himself to exercise). Hea?s a native Oregonian and thata?s saying something.  For the past 11 years hea?s met Greg Rucka for coffee every Wednesday pretty much without fail at the same place (we pretty much carved our names in the table). Matthew was also one of the original founders of Mercury Studio (now Periscope Studio); he got his start at Studiosaurus.<br /><br />He still reads comics, loves what he does, and works very hard. Loves to meet new people, but is really quiet (and has great hair).",
                            "autographs":"Complimentary at guest's discretion.(Twitter)",
                            "photographs":"",
                            "genre":"comic",
                            "links": [
                                {"linkname":"Website", "url":"http://www.matthewclarkartist.com/" },
                                {"linkname":"Twitter", "url":"https://twitter.com/emceeartist" }
                            ]
                        }
                    ]
                },
                {
                    "locationname":"Stage 2" ,
                    "guests": [
                        {
                            "guestid":"106146633306036834",
                            "guestname":"Sean Williams",
                            "time":"8am",
                            "largeimg":"http://ozcomiccon.com/images/banner/seanwilliams.jpg",
                            "smallimg":"http://ozcomiccon.com/images/banner/seanwilliamsresized.jpg",
                            "biotext": "Sean Williams was born in the dry, flat lands of South Australia, where he still lives with his wife and family. He has been called many things in his time, including a?the premier Australian speculative fiction writer of the agea (Aurealis), the a?Emperor of Sci-Fia (Adelaide Advertiser), and the a?King of Chameleonsa (Australian Book Review) for the diversity of his output.  That award-winning output includes thirty-five novels for readers all ages, seventy-five short stories across numerous genres, the odd published poem, and even a sci-fi musical.<br /><br />He is a multiple recipient of the Aurealis and Ditmar Awards in multiple categories and has been nominated for the Philip K. Dick Award, the Seiun Award, and the William Atheling Jr. Award for criticism. He received the a?SA Greata Literature Award in 2000 and the Peter McNamara Award for contributions to Australian speculative fiction in 2008.<br /><br />On the sci-fi front, he is best-known internationally for his original award-winning space opera series as well as several novels set in the Star Wars universe, many co-written with fellow-Adelaidean Shane Dix.  These include the Astropolis, Evergence, Orphans and Geodesica series, and the computer game tie-in The Force Unleasheda“the first such adaptation ever to debut at #1 on the New York Times bestseller list.  A series for young readers, The Fixers, pitted an increasingly lost protagonist against zombies, cyborgs, and vampires across numerous universes. His most recent releases in the Star Wars universe are The Old Republic: Fatal Alliance and The Force Unleashed II.",
                            "autographs":"Complimentary at guest's discretion.",
                            "photographs":"",
                            "genre":"comic",
                            "links": [
                                {"linkname":"website", "url":"http://www.seanwilliams.com" }
                            ]
                        },
                        {
                            "guestid":"17148603639603876",
                            "guestname":"Richard Dean Anderson",
                            "time":"10am",
                            "largeimg":"http://ozcomiccon.com/images/banner/richarddeananderson.jpg",
                            "smallimg":"http://ozcomiccon.com/images/banner/richarddeanandersonresized.jpg",
                            "biotext": "Richard Dean Anderson is probably best known as MacGyver, the clever and inventive nonviolent hero who solved problems in his own unique way for seven successful seasons on ABC. In his roles before and since, this gifted actor has continued to demonstrate his remarkable talent and versatility.<br /><br />Richard was born on January 23, 1950 in Minneapolis, Minnesota. His father, Stuart Anderson, taught English, drama, and humanities at a local high school, and is an accomplished jazz bassist. His mother, Jocelyn, is an artist, talented in both painting and sculpture. Richard is the eldest of four sons. He and his brothers, Jeffrey Scott, Thomas John, and James Stuart, grew up in the Minneapolis suburb of Roseville, where Richard developed early interests in sports, the arts, music, and acting.<br /><br />Like many boys growing up in Minnesota, Richard dreamed of becoming a professional hockey player. However, at the age of 16, he broke both arms, in separate accidents three weeks apart, while playing in high school hockey games. He put aside his dreams of playing professionally, though he still harbors a deep love for the sport. Richard talks of his restlessness growing up, his early desire to explore, and his adventures hitchhiking and hopping freight trains. At the age of 17, he took a 5641 mile bicycle trip from his home in Minnesota through Canada and Alaska, an experience which was sparked by his sense of adventure and discovery, but which also gave him a more centered sense of direction.",
                            "autographs":"Autograph from Richard .",
                            "photographs":"Photograph with Richard . SG1 double shot with Richard and Teryl Rothery 0. SG1 triple shot with Richard, Teryl Rothery and Corin Nemec 0.",
                            "genre":"acting",
                            "links": [
                                {"linkname":"Website", "url":"http://www.rdanderson.com/" },
                                {"linkname":"Twitter", "url":"https://twitter.com/andersonrdean" }
                            ]
                        }
                    ]
                }
            ]
        }
    ]

I have object class named Name, and I want to put all the data of the name(perth) jsonobject as a single object of the Name class. But it is not adding data in the arraylist correctly, more clearly the guestid, guestnameetc tag values are being saved but overwrites the previous one. Here is my parsing code:

我有一个名为 Name 的对象类,我想把 name(perth) jsonobject 的所有数据作为 Name 类的单个对象。但它没有正确地在数组列表中添加数据,更清楚的是,guestid, guestnameetc 标签值正在被保存但覆盖了前一个。这是我的解析代码:

public ArrayList<Guest> parseInitiator() throws ClientProtocolException,
            IOException, JSONException {

        InputStream is = new FileInputStream(new File(Url));
        int size = is.available();
        byte[] buffer = new byte[size];
        is.read(buffer);
        is.close();
        String mResponse = new String(buffer);

        JSONObject first = new JSONObject(mResponse);

        JSONArray firstarray = first.getJSONArray("location");

        ArrayList<Guest> parsedData = new ArrayList<Guest>();
        for (int i = 0; i < firstarray.length(); i++) {

            JSONObject jonj = firstarray.getJSONObject(i);

             name = jonj.getString("name");

            JSONArray confarray = jonj.getJSONArray("conferencelocation");
            locationname  = new String[confarray.length()];
            for (int j = 0; j < confarray.length(); j++) {
                JSONObject conobbj = confarray.getJSONObject(j);

                 locationname[j] = conobbj.getString("locationname");

                JSONArray guestarray = conobbj.getJSONArray("guests");
                guestid= new String[guestarray.length()];
                guestname= new String[guestarray.length()];
                time= new String[guestarray.length()];
                largeimg= new String[guestarray.length()];
                smallimg= new String[guestarray.length()];
                biotext= new String[guestarray.length()];
                autographs= new String[guestarray.length()];
                photographs= new String[guestarray.length()];
                genre= new String[guestarray.length()];

                for (int k = 0; k < guestarray.length(); k++) {
                    JSONObject guestobbj = guestarray.getJSONObject(k);

                     guestid[k] = guestobbj.getString("guestid");
                     guestname[k] = guestobbj.getString("guestname");
                     time[k] = guestobbj.getString("time");
                     largeimg[k] = guestobbj.getString("largeimg");
                     smallimg[k] = guestobbj.getString("smallimg");
                     biotext[k] = guestobbj.getString("biotext");
                     autographs[k] = guestobbj.getString("autographs");
                     photographs[k] = guestobbj.getString("photographs");
                     genre[k] = guestobbj.getString("genre");

                    JSONArray linkar = guestobbj.getJSONArray("links");
                    arlink= new String[linkar.length()];
                    arurl= new String[linkar.length()];
                    for (int l = 0; l < linkar.length(); l++) {
                        JSONObject linkobj = linkar.getJSONObject(l);


                        arlink[l] = linkobj.getString("linkname");
                        arurl[l] = linkobj.getString("url");

                    }

                }

            }


            parsedData.add(new Guest(name,locationname, guestid, guestname, time, largeimg, smallimg, biotext,
                    autographs, photographs, genre,arlink, arurl));


        }

        return parsedData;

    }

Can anyone make me clear about the mistake I have made?

谁能让我清楚我所犯的错误?

回答by Simon Dorociak

So here is my solution:

所以这是我的解决方案:

JSONObject first = new JSONObject(mResponse);

JSONArray locArr = first.getJSONArray("location"); // contains one object
JSONObject locArrObj = locArr.getJSONObject(0); // cotains one "out" array

JSONArray conferenceLocArr = locArrObj.getJSONArray("conferencelocation");
// this array has two objects and each object has array
JSONObject o = null;
JSONArray arr = null;

for (int i = 0; i < conferenceLocArr.length(); i++) {
   o = conferenceLocArr.getJSONObject(i); // it has one array
   arr = o.getJSONArray("guests");
   //  do your work with Stage 1 and guests
   // and for second object for Stage 2 and guests.
}