如何解析嵌套的JSON数组在Android的一个对象 [英] How to parse nested json arrays in a single object in android

查看:100
本文介绍了如何解析嵌套的JSON数组在Android的一个对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JSON里面有多个嵌套JSONARRAY的。这里是片段。

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

{
    "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":"$30 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 $40.",
                            "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 DC’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). He’s a native Oregonian and that’s saying something.  For the past 11 years he’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 “the premier Australian speculative fiction writer of the age†(Aurealis), the “Emperor of Sci-Fi†(Adelaide Advertiser), and the “King of Chameleons†(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 “SA Great†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 Unleashedâ€"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 $50.",
                            "photographs":"Photograph with Richard $80. SG1 double shot with Richard and Teryl Rothery $150. SG1 triple shot with Richard, Teryl Rothery and Corin Nemec $200.",
                            "genre":"acting",
                            "links": [
                                {"linkname":"Website", "url":"http://www.rdanderson.com/" },
                                {"linkname":"Twitter", "url":"https://twitter.com/andersonrdean" }
                            ]
                        }
                    ]
                }
            ]
        }
    ]

我有一个名为名称的对象类,我想把名字(珀斯)的JSONObject的所有数据作为名称类的一个对象。但它不加入ArrayList中的数据正确,更清晰的 guestid,guest虚拟机名称等标签值被保存,但覆盖previous之一。这里是我的分析code:

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, guestname etc tag values are being saved but overwrites the previous one. Here is my parsing code:

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?

推荐答案

因此​​,这里是我的解决方案:

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.
}

这篇关于如何解析嵌套的JSON数组在Android的一个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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