2017-10-14 19 views
0

私はAPIからデータを取得するためのチュートリアルに従っていますが、現在は自分のモデルでは機能していないようです。応答は次のように入れ子になっているがネストされたJSON値の取得

List<Show> items = new Gson().fromJson(response.toString(), new TypeToken<List<Show>>() { 
}.getType()); 

:目標は何

{ 
    "page": 1, 
    "total_results": 41, 
    "total_pages": 3, 
    "results": [{ 
     "original_name": "Power Rangers", 
     "genre_ids": [10759, 10762, 10765], 
     "name": "Power Rangers", 
     "popularity": 90.646128, 
     "origin_country": ["US"], 
     "vote_count": 111, 
     "first_air_date": "1993-08-28", 
     "backdrop_path": "\/wCLLq7eV6AgpRQMLz6VRHkYVTDV.jpg", 
     "original_language": "en", 
     "id": 2328, 
     "vote_average": 4.8, 
     "overview": "A team of teenagers with attitude are recruited to save Angel Grove from the evil witch, Rita Repulsa, and later, Lord Zedd, Emperor of all he sees, and their horde of monsters.", 
     "poster_path": "\/zyHCzQUkgaemgCMEplqAqsp83SA.jpg" 
    }, { 
     "original_name": "ドラゴンボール改「カイ」", 
     "genre_ids": [16, 35, 10759, 10765], 
     "name": "Dragon Ball Z Kai", 
     "popularity": 89.606367, 
     "origin_country": ["JP"], 
     "vote_count": 60, 
     "first_air_date": "2009-04-05", 
     "backdrop_path": "\/9OYqeyZHlxlIsM2nfDiZ58EaWl9.jpg", 
     "original_language": "ja", 
     "id": 61709, 
     "vote_average": 6, 
     "overview": "Rejoin Goku and his friends in a series of cosmic battles! Toei has redubbed, recut, and cleaned up the animation of the original 1989 animated series. The show's story arc has been refined to better follow the comic book series on which it is based. The show also features a new opening and ending. In the series, martial artist Goku, and his various friends, battle increasingly powerful enemies to defend the world against evil. Can Earth's defender defeat demons, aliens, and other villains?", 
     "poster_path": "\/j8BTh7MKA3rh4VXEmRsnlro5ntI.jpg" 
    }, { 
     "original_name": "A Herdeira", 
     "id": 73951, 
     "name": "A Herdeira", 
     "popularity": 83.235889, 
     "vote_count": 1, 
     "vote_average": 2, 
     "first_air_date": "2017-09-24", 
     "poster_path": "\/Acf1EEhOZwDNB0IuuICwyIDfYqF.jpg", 
     "genre_ids": [18, 10766], 
     "original_language": "pt", 
     "backdrop_path": "\/lQFzeBxQBSyHwtaGcsOd9eKnELr.jpg", 
     "overview": "The story of a girl created by the gypsy community but who in fact is heiress of a great empire. The woman who robbed her in the past now sees her future threatened. The return of the Heiress unleashes struggles of power and affections and a love to withstand anything.", 
     "origin_country": ["PT"] 
    }, { 
     "original_name": "ポケモン", 
     "genre_ids": [16, 10759], 
     "name": "Pokémon", 
     "popularity": 82.040011, 
     "origin_country": ["JP"], 
     "vote_count": 145, 
     "first_air_date": "1997-04-01", 
     "backdrop_path": "\/uxBFkJNwp9DEIE7k6YhKAorVpkp.jpg", 
     "original_language": "ja", 
     "id": 60572, 
     "vote_average": 5.9, 
     "overview": "Join Ash Ketchum, accompanied by his partner Pikachu, as he travels through many regions, meets new friends and faces new challenges on his quest to become a Pokémon Master.", 
     "poster_path": "\/2pcTUs20ysCdA6DZclaPmGXD6ph.jpg" 
    }, { 
     "original_name": "Paixão", 
     "id": 73953, 
     "name": "Paixão", 
     "popularity": 80.38428, 
     "vote_count": 0, 
     "vote_average": 0, 
     "first_air_date": "", 
     "poster_path": "\/1pG5X5xalswbn9KkYz2pCQzEPQt.jpg", 
     "genre_ids": [35, 18], 
     "original_language": "pt", 
     "backdrop_path": null, 
     "overview": "With Algarve and South Africa as main stages, Paixão tells the story of a love that was destroyed by a lie. This is the story of a man determined to fight for justice and to recover ten years of his life and an unshakable love that resists time and all threats.", 
     "origin_country": ["PT"] 
    }, { 
     "original_name": "My Little Pony: Friendship Is Magic", 
     "genre_ids": [16, 35, 10751, 10762, 10765], 
     "name": "My Little Pony: Friendship Is Magic", 
     "popularity": 68.117697, 
     "origin_country": ["US", "CA"], 
     "vote_count": 45, 
     "first_air_date": "2010-10-10", 
     "backdrop_path": "\/8iSSsncJ9DhP7k6qhl7heEe4QVH.jpg", 
     "original_language": "en", 
     "id": 33765, 
     "vote_average": 6.3, 
     "overview": "\"Get your muzzle out of those books and make some friends!\" That's what Princess Celestia tells Twilight Sparkle. She may be the smartest unicorn in Equestria, but Twilight Sparkle gets an \"incomplete\" in friendship. There's more to life than learning magic, after all -- so she goes to Ponyville on a mission to make friends. There she meets five special ponies who take her on exciting adventures and teach her the most powerful magic of all ... the magic of friendship!", 
     "poster_path": "\/4gBSd6TGzIn3VC6IhPrRHavXy6S.jpg" 
    }, { 
     "original_name": "ドラゴンボール超(スーパー)", 
     "genre_ids": [16, 9648, 10759], 
     "name": "Dragon Ball Super", 
     "popularity": 46.283499, 
     "origin_country": ["JP"], 
     "vote_count": 136, 
     "first_air_date": "2015-07-05", 
     "backdrop_path": "\/yJAOi2n0VYBEXdPI1NXv5FiOcBX.jpg", 
     "original_language": "ja", 
     "id": 62715, 
     "vote_average": 7, 
     "overview": "Set just after the events of the Buu Saga of Dragon Ball Z, a deadly threat awakens once more. People lived in peace without knowing who the true heroes were during the devastating battle against Majin Buu. The powerful Dragon Balls have prevented any permanent damage, and our heroes also continue to live a normal life. In the far reaches of the universe, however, a powerful being awakens early from his slumber, curious about a prophecy of his defeat.\n\nJoin Gokuu, Piccolo, Vegeta, Gohan, and the rest of the Dragon Ball crew as they tackle the strongest opponent they have ever faced. Beerus, the god of destruction, now sets his curious sights on Earth. Will the heroes save the day and prevent earth's destruction? Or will the whims of a bored god prove too powerful for the Saiyans? Gokuu faces impossible odds once more and fights for the safety of his loved ones and the planet.", 
     "poster_path": "\/qEUrbXJ2qt4Rg84Btlx4STOhgte.jpg" 
    }, { 
     "original_name": "Bigg Boss", 
     "genre_ids": [10764], 
     "name": "Bigg Boss", 
     "popularity": 43.713702, 
     "origin_country": ["IN"], 
     "vote_count": 1, 
     "first_air_date": "2006-11-03", 
     "backdrop_path": null, 
     "original_language": "hi", 
     "id": 11436, 
     "vote_average": 6, 
     "overview": "Bigg Boss is a reality TV programme broadcast in India. It follows the Big Brother format, which was first developed by Endemol in the Netherlands.", 
     "poster_path": "\/bPbGjPPQmd44SpxAJYqiLYXPemX.jpg" 
    }, { 
     "original_name": "Austin City Limits", 
     "genre_ids": [99], 
     "name": "Austin City Limits", 
     "popularity": 34.799205, 
     "origin_country": ["US"], 
     "vote_count": 4, 
     "first_air_date": "1975-01-01", 
     "backdrop_path": "\/88r7LdK83JtLkVh1m62XKSIOpMJ.jpg", 
     "original_language": "en", 
     "id": 10472, 
     "vote_average": 7, 
     "overview": "Austin City Limits is an American public television music program recorded live in Austin, Texas by Public Broadcasting Service Public television member station KLRU, and broadcast on many PBS stations around the United States. The show helped Austin to become widely known as the \"Live Music Capital of the World,\" and is the only television show to receive the National Medal of Arts, which it was awarded in 2003.\n\nInitially created to celebrate the music of Texas—featuring western swing, Texas blues, Tejano music, progressive country, and rock n' roll—the series has gone on to feature regional, national and international artists performing a wide range of musical styles, including jazz, alternative country, alternative rock, folk music, and jam band.", 
     "poster_path": "\/jfY7ZqV7WhfE7kFovO58y0EBjFy.jpg" 
    }, { 
     "original_name": "Game Shakers", 
     "genre_ids": [35], 
     "name": "Game Shakers", 
     "popularity": 27.172162, 
     "origin_country": ["US"], 
     "vote_count": 5, 
     "first_air_date": "2015-09-12", 
     "backdrop_path": "\/qQoKJoJnKdWCBocQPc6Vqq2DIGL.jpg", 
     "original_language": "en", 
     "id": 64264, 
     "vote_average": 5.2, 
     "overview": "A live-action sitcom about two 12-year-old girls who start a multi-million-dollar gaming company and take on rap superstar Double G as a business partner.", 
     "poster_path": "\/84BvYikLEFvwKoZk4FIrRd5YtGH.jpg" 
    }, { 
     "original_name": "Dirk Gently's Holistic Detective Agency", 
     "genre_ids": [35, 10765], 
     "name": "Dirk Gently's Holistic Detective Agency", 
     "popularity": 23.411494, 
     "origin_country": ["GB", "US"], 
     "vote_count": 85, 
     "first_air_date": "2016-10-22", 
     "backdrop_path": "\/tQKKzLbqNWaTufmrcQku7pPcv5j.jpg", 
     "original_language": "en", 
     "id": 67773, 
     "vote_average": 7.7, 
     "overview": "A comedic thriller that follows the bizarre adventures of eccentric “holistic” detective Dirk Gently and his reluctant assistant Todd. An adaptation of Douglas Adams’ wildly successful comic novels.", 
     "poster_path": "\/q8oMpXPEAUJJ0KztsRs5K51T2lo.jpg" 
    }, { 
     "original_name": "Sonic Boom", 
     "genre_ids": [16, 35, 10759, 10765], 
     "name": "Sonic Boom", 
     "popularity": 21.372733, 
     "origin_country": ["FR", "US"], 
     "vote_count": 5, 
     "first_air_date": "2014-11-08", 
     "backdrop_path": "\/9145DdWxUAL2G7pUGHCagPqIrAg.jpg", 
     "original_language": "en", 
     "id": 62211, 
     "vote_average": 3.8, 
     "overview": "The speedy blue hedgehog gets a new look in this comedy\/adventure series that sees him battling a familiar foe with sidekick Tails and pals Knuckles, Amy and Sticks. The gang tries to ward off the evil plans of Dr. Eggman, who is hellbent on taking over the world. Sonic faces regular battles with Eggman's henchmen, including loyal robots Orbot and Cubot, evil interns, and giant, robotic monsters.", 
     "poster_path": "\/2DSPdtWIpbYQCgyCDEfgkLtfEH8.jpg" 
    }, { 
     "original_name": "Marvel's Spider-Man", 
     "genre_ids": [16, 10765], 
     "name": "Marvel's Spider-Man", 
     "popularity": 21.158794, 
     "origin_country": ["US"], 
     "vote_count": 6, 
     "first_air_date": "2017-08-19", 
     "backdrop_path": "\/1K8EidFcHrh4x41O4urE1xG81fa.jpg", 
     "original_language": "en", 
     "id": 72705, 
     "vote_average": 10, 
     "overview": "An insecure but courageous and intelligent teen named Peter Parker, a new student of Midtown High, is bitten by a radioactive spider and given powers. He becomes a hero named Spider-Man after the death of his uncle and he must adapt to this new way of life.", 
     "poster_path": "\/ty4elPPA9zifK9yCVMlDq1dS1Y.jpg" 
    }, { 
     "original_name": "Biggest Deal", 
     "genre_ids": [10764], 
     "name": "Biggest Deal", 
     "popularity": 21.082701, 
     "origin_country": ["PT"], 
     "vote_count": 0, 
     "first_air_date": "2017-10-01", 
     "backdrop_path": "\/nhIQzW9fF3TvxU1PaaIWWeziIZg.jpg", 
     "original_language": "pt", 
     "id": 74211, 
     "vote_average": 0, 
     "overview": "One house and 16 celebrities divided into 4 teams with the aim of managing 4 businesses. This format takes each of the celebrity teams to run a pizzeria, car wash, bed and breakfast, and beauty salon. The profits made are given to solidarity institutions. The celebrities are closed in a home with 24 hour monitoring and are evaluated based on the business results and on the public vote.", 
     "poster_path": "\/bTRcZ05SbM2rzFqRYrXytas4XFp.jpg" 
    }, { 
     "original_name": "3月のライオン", 
     "genre_ids": [16, 18], 
     "name": "March Comes in Like a Lion", 
     "popularity": 20.696228, 
     "origin_country": ["JP"], 
     "vote_count": 7, 
     "first_air_date": "2016-10-08", 
     "backdrop_path": "\/5aeUov0R9fYF2UcC9ulpr924rYT.jpg", 
     "original_language": "ja", 
     "id": 65336, 
     "vote_average": 7.9, 
     "overview": "Rei is a 17-year old professional shōgi player, who lives by himself, not having a real family, and has scarcely any friends. Among his acquaintances is a family, which consists of a young woman, Akari, and two young girls, Hinata and Momo, and who also keep a numerous number of cats.", 
     "poster_path": "\/ecYjqBuRcYdZLFGLhyPtdBbDV3z.jpg" 
    }, { 
     "original_name": "The Woodwright's Shop", 
     "genre_ids": [], 
     "name": "The Woodwright's Shop", 
     "popularity": 20.526514, 
     "origin_country": ["US"], 
     "vote_count": 3, 
     "first_air_date": "1981-01-01", 
     "backdrop_path": "\/v8FCKmzvqogZroLDEswvPolcMT.jpg", 
     "original_language": "en", 
     "id": 15072, 
     "vote_average": 9.3, 
     "overview": "The Woodwright's Shop is a traditional woodworking show hosted by Roy Underhill on the Public Broadcasting Service in the United States. It is one of the longest running \"how to\" shows on PBS. Since its debut in 1979, the show has aired over 400 episodes. The first two seasons were broadcast only on public TV in North Carolina; the season numbering was restarted when the show went national in 1981. It is still filmed at the UNC-TV studios in Research Triangle Park, North Carolina.", 
     "poster_path": "\/2iQHN0Pqg9MTQVNqCQjqUYJOOWm.jpg" 
    }, { 
     "original_name": "ボールルームへようこそ", 
     "genre_ids": [16, 35, 18], 
     "name": "Welcome to the Ballroom", 
     "popularity": 19.702918, 
     "origin_country": ["JP"], 
     "vote_count": 4, 
     "first_air_date": "2017-07-08", 
     "backdrop_path": "\/7AywhjZIVl6aVplPI12vyMWS9tJ.jpg", 
     "original_language": "ja", 
     "id": 72362, 
     "vote_average": 9.3, 
     "overview": "Tatara is an average middle school student with no particular dreams until an unexpected incident draws him into the fascinating world of ballroom dancing. “If I can just find one thing to be passionate about...” He dives into the world of dance, believing it's his opportunity to change. “Dance is a passion!”", 
     "poster_path": "\/o3qKiKaGDnvCcTDU2ntz6eeS0hh.jpg" 
    }, { 
     "original_name": "밥상을 차리는 남자", 
     "genre_ids": [35, 18], 
     "name": "Man Who Sets The Table", 
     "popularity": 17.866542, 
     "origin_country": ["KR"], 
     "vote_count": 2, 
     "first_air_date": "2017-09-02", 
     "backdrop_path": "\/pB4TRFqUxwotM4rykB3QoLzgVZ4.jpg", 
     "original_language": "ko", 
     "id": 73576, 
     "vote_average": 8, 
     "overview": "Lee Roo-Ri tries to get a job at big company, but she gives up. She doesn't have a good relationship with her strict father. Lee Roo-Ri decides to travel to a foreign country to get away. There, she meets Jung Tae-Yang who goes by the YOLO motto. He wanders around the world and places priority on his happiness, but he also carries an emotional wound.\n\nAfter she meets Jung Tae-Yang, Lee Roo-Ri has a turning point of her life.", 
     "poster_path": "\/eDadLdEM6YMNJcEmVy1U59hqxl5.jpg" 
    }, { 
     "original_name": "도둑놈, 도둑님", 
     "genre_ids": [80, 18], 
     "name": "The Good Thieves", 
     "popularity": 17.699403, 
     "origin_country": ["KR"], 
     "vote_count": 8, 
     "first_air_date": "2017-05-13", 
     "backdrop_path": "\/vSNJPM26agjpJ8JoTJwR5eL7dK7.jpg", 
     "original_language": "ko", 
     "id": 71640, 
     "vote_average": 3.1, 
     "overview": "The story centers on thieves who strike against people in high power who try to control Korea.", 
     "poster_path": "\/twQLMej5SAPVwNfhpFzponN62T2.jpg" 
    }, { 
     "original_name": "PBS NewsHour Weekend", 
     "genre_ids": [10763], 
     "name": "PBS NewsHour Weekend", 
     "popularity": 17.673767, 
     "origin_country": ["US"], 
     "vote_count": 0, 
     "first_air_date": "2013-09-07", 
     "backdrop_path": "\/r24H1UEMjSm6hMs9JjU1eBVV103.jpg", 
     "original_language": "en", 
     "id": 58287, 
     "vote_average": 0, 
     "overview": "A summary of the day’s national and international news, using renowned experts to provide in-depth analysis. Each weekend broadcast contains original, in-depth field reporting on topics including education, healthcare, the economy, energy, science and technology, religion, finance and the arts.", 
     "poster_path": "\/6aeXBSYRqnbLZjhjgK9M12odJly.jpg" 
    }] 
} 

、モデルが唯一できるよう、この応答の中に「結果」を得ることですこれは、次のようにデータをフェッチこれらのフィールドを取る。私はこれらの名前のほとんどが定義されているシンプルなShowモデルを持っています。私はそれをどこで見たことがないが、私はちょうどList<Show> items = new Gson().fromJson(response.get("results").toString() ..)何かを行うことができた機能はありませんか?注:私はレスポンスの解析について読んだことがありますが、上記のようにこのインデックスを取得できるPythonをよく知っているので、ここでも可能ですか?

EDIT:より多くのコード

private void fetch() { 
    JsonArrayRequest request = new JsonArrayRequest(URL, 
      response -> { 
       if (response == null) { 
        Toast.makeText(getApplicationContext(), "Couldn't fetch the menu! Pleas try again.", Toast.LENGTH_LONG).show(); 
        return; 
       } 

       JsonArray results = new Gson().fromJson(response.toString(), JsonObject.class).getAsJsonArray("results"); 

       List<Show> items = new Gson().fromJson(results, new TypeToken<List<Show>>() {}.getType()); 

       showlist.clear(); 
       showlist.addAll(items); 
       mAdapter.notifyDataSetChanged(); 
      }, error -> { 
       Log.d(TAG, "Error: " + error.getMessage()); 
       Toast.makeText(getApplicationContext(), "Error: " + error.getMessage(), Toast.LENGTH_SHORT).show(); 
      }); 

    TApplication.getInstance().addToRequestQueue(request); 
} 
+0

「response.toString()」がこのJSONを返すことを100%確信していますか?追加の入れ子なしで?また、使用しているGSONのバージョンは?私は: 'compile 'com.google.code.gson:gson:2.8.2'' –

+0

応答はJSONArray(これのためにVolleyライブラリを使用しています)をtoJsonでtoString()する必要がありますJSONArrayをそこに置くときにメソッドを解決できないので、 – dnsko

+0

いいえ、投稿したJSONは配列ではなく、オブジェクトです。 'response.toString()'が返すものを正確に貼り付けることができますか? –

答えて

1

あなたが "結果" 列その方法を取得することができます:

Gson gson = new Gson(); 
JsonElement element = gson.fromJson(input, JsonElement.class); 
JsonObject object = element.getAsJsonObject(); 
assertTrue(object.get("results").isJsonArray()); 

入力は、あなたの文字列化JSONです。その後、object.get("results")fromJSON(, new TypeToken)に渡すと、リストが表示されます。

もちろん、この部分(あなたのオブジェクトに変換)が動作していると仮定します。

編集:

ワンライナー:

JsonArray results = new Gson().fromJson(input, JsonObject.class).getAsJsonArray("results"); 

別の編集:

はい、あなたは完全なオブジェクト表現を提供する必要はありません。追加のJSON項目は無視されます。チャット議論の

static class Show { 
    String original_name; 
} 

@Test 
public void show_json() throws Exception { 
    String input = "{\n" + 
      " \"page\": 1,\n" + 
      " \"total_results\": 41,\n" + 
      " \"total_pages\": 3,\n" + 
      " \"results\": [{\n" + 
      "  \"original_name\": \"Power Rangers\",\n" + 
      "  \"genre_ids\": [10759, 10762, 10765],\n" + 
      "  \"name\": \"Power Rangers\",\n" + 
      "  \"popularity\": 90.646128,\n" + 
      "  \"origin_country\": [\"US\"],\n" + 
      "  \"vote_count\": 111,\n" + 
      "  \"first_air_date\": \"1993-08-28\",\n" + 
      "  \"backdrop_path\": \"\\/wCLLq7eV6AgpRQMLz6VRHkYVTDV.jpg\",\n" + 
      "  \"original_language\": \"en\",\n" + 
      "  \"id\": 2328,\n" + 
      "  \"vote_average\": 4.8,\n" + 
      "  \"overview\": \"A team of teenagers with attitude are recruited to save Angel Grove from the evil witch, Rita Repulsa, and later, Lord Zedd, Emperor of all he sees, and their horde of monsters.\",\n" + 
      "  \"poster_path\": \"\\/zyHCzQUkgaemgCMEplqAqsp83SA.jpg\"\n" + 
      " }, {\n" + 
      "  \"original_name\": \"ドラゴンボール改「カイ」\",\n" + 
      "  \"genre_ids\": [16, 35, 10759, 10765],\n" + 
      "  \"name\": \"Dragon Ball Z Kai\",\n" + 
      "  \"popularity\": 89.606367,\n" + 
      "  \"origin_country\": [\"JP\"],\n" + 
      "  \"vote_count\": 60,\n" + 
      "  \"first_air_date\": \"2009-04-05\",\n" + 
      "  \"backdrop_path\": \"\\/9OYqeyZHlxlIsM2nfDiZ58EaWl9.jpg\",\n" + 
      "  \"original_language\": \"ja\",\n" + 
      "  \"id\": 61709,\n" + 
      "  \"vote_average\": 6,\n" + 
      "  \"overview\": \"Rejoin Goku and his friends in a series of cosmic battles! Toei has redubbed, recut, and cleaned up the animation of the original 1989 animated series. The show's story arc has been refined to better follow the comic book series on which it is based. The show also features a new opening and ending. In the series, martial artist Goku, and his various friends, battle increasingly powerful enemies to defend the world against evil. Can Earth's defender defeat  demons, aliens, and other villains?\",\n" + 
      "  \"poster_path\": \"\\/j8BTh7MKA3rh4VXEmRsnlro5ntI.jpg\"\n" + 
      " }]\n" + 
      "}"; 


    JsonArray results = new Gson().fromJson(input, JsonObject.class).getAsJsonArray("results"); 

    List<Show> items = new Gson().fromJson(results, new TypeToken<List<Show>>() {}.getType()); 

    assertTrue(items.get(0).original_name.equals("Power Rangers")); 
} 

結果::彼らはJsonObjectのようなクラス名を共有するため

とても確かに、同じファイルにorg.jsoncom.google.gsonを使用して混乱することができるショークラスの唯一の財産との完全な例そのうちの1つに完全修飾名を使用してください:

+0

Showモデルでは、正しい結果を解析するために「結果」に渡されるすべての属性を必須にしていますか?私が必要としないいくつかのアイテム@JakubPiskorz – dnsko

+0

もちろん、フルクラスを提供する必要はありません。私の編集を参照してください。 –

+0

ああ、私は 'org.json.JSONException:Value {" page ":1、.... org.json.JSONObject型のJSONArray'に変換できませんが、 – dnsko

関連する問題