Как создать новую модель для ответа нескольких моделей на вызов Web API - PullRequest
0 голосов
/ 19 февраля 2020

Существует метод GET из TMDB API, который может возвращать 3 типа смешанных данных в одном массиве, mov ie, tv и actor. В настоящее время я должен был создать эти 3 модели, но как я могу создать одну модель данных со всеми этими тремя типами данных?

Ну, моя цель - перечислить все типы результатов поиска в табличном представлении, например, когда я даю «Миллиарды», в нем должны быть перечислены телесериалы с названием «Миллиарды», а также «Mov ie» и «Актер» с тем же именем.

/ / / как показано ниже, результат возвращается из Web API, элемент с 14 или 15 элементами может быть Mov ie или элементом TV, а левый - Actor с 9 элементами.

(root): {} 4 Items
  page: 1
  total_results: 16
  total_pages: 1
results [] 16 Items
  0: {} 14 Items
  1: {} 15 Items
  2: {} 15 Items
  3: {} 9 Items
  4: {} 15 Items
  5: {} 15 Items
  6: {} 9 Items
  7: {} 9 Items
  8: {} 15 Items
  ...

Multi search: GET / search / multi

Поиск нескольких моделей за один запрос. Multi search в настоящее время поддерживает поиск фильмов, телешоу и людей по одному запросу.

/ / / Обновление ответа json от сервера для мульти-поиска. Возвращенные данные json похожи на результаты [Mov ie, Mov ie, Mov ie, TV, Actor ...], который содержит 3 типа элементов и без последовательности, также может происходить много элементов одного типа. раз в массиве на основе вашего имени поискового запроса. Таким образом, как создать модель для принятия вышеуказанных результатов [] json data?

{
  "page": 1,
  "total_results": 16,
  "total_pages": 1,
  "results": [
    {
      "original_name": "Billions",
      "genre_ids": [
        18
      ],
      "media_type": "tv",
      "name": "Billions",
      "popularity": 32.444,
      "origin_country": [
        "US"
      ],
      "vote_count": 328,
      "first_air_date": "2016-01-17",
      "backdrop_path": "/6f3s7NbujF9NGBIdBQhRJcZAbFy.jpg",
      "original_language": "en",
      "id": 62852,
      "vote_average": 7.7,
      "overview": "A complex drama about power politics in the world of New York high finance. \n\nShrewd, savvy U.S. Attorney Chuck Rhoades and the brilliant, ambitious hedge fund king Bobby \"Axe\" Axelrod are on an explosive collision course, with each using all of his considerable smarts, power and influence to outmaneuver the other. The stakes are in the billions in this timely, provocative series.",
      "poster_path": "/3VlVadslWLbOJtp4VQ6VkdAwmpV.jpg"
    },
    {
      "vote_count": 5,
      "popularity": 3.034,
      "id": 173327,
      "video": false,
      "media_type": "movie",
      "vote_average": 7.1,
      "title": "From Bedrooms to Billions",
      "release_date": "2014-10-03",
      "original_language": "en",
      "original_title": "From Bedrooms to Billions",
      "genre_ids": [
        99
      ],
      "backdrop_path": "/iRVufH3NyLHIhyVpJHOdm3dRTgz.jpg",
      "adult": false,
      "overview": "From Bedrooms to Billions is a 2014 documentary film by British filmmakers Anthony Caulfield and Nicola Caulfield that tells the story of the British video games industry from 1979 to the present day. The film focuses on how the creativity and vision of a relatively small number of individuals allowed the UK to play a key, pioneering role in the shaping of the billion dollar video games industry which today dominates the modern world's entertainment landscape. The film features interviews with major British game designers, journalists and musicians from across the last 30 years.",
      "poster_path": "/fYImGFVmmYbksWJwA5DQE4A3jqS.jpg"
    },
    {
      "vote_count": 0,
      "popularity": 0.841,
      "id": 566190,
      "video": false,
      "media_type": "movie",
      "vote_average": 0,
      "title": "Billions",
      "release_date": "1920-12-06",
      "original_language": "en",
      "original_title": "Billions",
      "genre_ids": [
        35
      ],
      "backdrop_path": null,
      "adult": false,
      "overview": "Billions is a lost 1920 American silent comedy film produced by and starring Alla Nazimova and distributed by Metro Pictures. Ray Smallwood directed. It is based on a French play, L'Homme riche, by Jean Jose Frappa and Henry Dupuy-Mazuel.",
      "poster_path": "/tyg1N4tp4NU52xpxPr3CAO0o4QG.jpg"
    },
    {
      "known_for_department": "Acting",
      "id": 1547859,
      "name": "Jonathan Billions",
      "known_for": [
        {
          "original_name": "The Walking Dead",
          "genre_ids": [
            18,
            10759,
            10765
          ],
          "media_type": "tv",
          "name": "The Walking Dead",
          "origin_country": [
            "US"
          ],
          "vote_count": 4517,
          "first_air_date": "2010-10-31",
          "backdrop_path": "/wXXaPMgrv96NkH8KD1TMdS2d7iq.jpg",
          "original_language": "en",
          "id": 1402,
          "vote_average": 7.3,
          "overview": "Sheriff's deputy Rick Grimes awakens from a coma to find a post-apocalyptic world dominated by flesh-eating zombies. He sets out to find his family and encounters many other survivors along the way.",
          "poster_path": "/5l10EjdgPxu8Gbl5Ww6SWkVQH6T.jpg"
        },
        {
          "poster_path": "/y1VT2NoBOx3aC2exhkyN9AGUkMR.jpg",
          "vote_count": 834,
          "video": false,
          "media_type": "movie",
          "id": 333385,
          "adult": false,
          "backdrop_path": "/pEQVSTEuYOOBAzbD7VzBea2KlCs.jpg",
          "original_language": "en",
          "original_title": "Mr. Right",
          "genre_ids": [
            28,
            35,
            10749
          ],
          "title": "Mr. Right",
          "vote_average": 6.4,
          "overview": "A girl falls for the \"perfect\" guy, who happens to have a very fatal flaw: he's a hitman on the run from the crime cartels who employ him.",
          "release_date": "2016-02-29"
        },
        {
          "poster_path": "/cbpv3Ocs772JVRLT6xlRJsiPwFp.jpg",
          "vote_count": 102,
          "video": false,
          "media_type": "movie",
          "id": 367551,
          "adult": false,
          "backdrop_path": "/xVqO8aah6HgLfP0bsG9YBidpNQJ.jpg",
          "original_language": "en",
          "original_title": "American Hero",
          "genre_ids": [
            28,
            35,
            878
          ],
          "title": "American Hero",
          "vote_average": 5.2,
          "overview": "Melvin, a reluctant hero who is far from super, has been suppressing his telekinetic powers for years with booze, drugs, and women. In the process, he has failed at practically everything, most of all as a parent to his son. After a brush with death, Melvin decides to use his powers for good and clean up the streets of New Orleans with the help of his best friend/definitely-not-a-sidekick, Lucille. For a man who can do the impossible, it might be a fight even he can’t win.",
          "release_date": "2015-12-11"
        }
      ],
      "popularity": 1.4,
      "profile_path": "/51C28GwY9XYx9ELLiaHEaPsa2nu.jpg",
      "adult": false,
      "media_type": "person",
      "gender": 0
    },
    {
      "poster_path": "/xys6Ii7J0tYgaXVcStts7r5sAcn.jpg",
      "popularity": 4.262,
      "vote_count": 11,
      "video": false,
      "media_type": "movie",
      "id": 339586,
      "adult": false,
      "backdrop_path": "/2RdKldFMbdm2eXB1NJljf367tJ7.jpg",
      "original_language": "en",
      "original_title": "From Bedrooms to Billions: The Amiga Years",
      "genre_ids": [
        99
      ],
      "title": "From Bedrooms to Billions: The Amiga Years",
      "vote_average": 7.4,
      "overview": "A feature documentary that explores the influence of the Commodore Amiga and how it took video game development, music and publishing to a whole new level and changed the video games industry forever.",
      "release_date": "2016-05-10"
    },
    {
      "vote_count": 7,
      "popularity": 1.16,
      "id": 363551,
      "video": false,
      "media_type": "movie",
      "vote_average": 8.3,
      "title": "Billions in Change",
      "release_date": "2015-10-04",
      "original_language": "en",
      "original_title": "Billions in Change",
      "genre_ids": [
        99
      ],
      "backdrop_path": null,
      "adult": false,
      "overview": "The world is facing some huge problems. There’s a lot of talk about how to solve them. But talk doesn’t reduce pollution, or grow food, or heal the sick. That takes doing. This film is the story about a group of doers, the elegantly simple inventions they have made to change the lives of billions of people, and the unconventional billionaire spearheading the project.",
      "poster_path": "/ryiRPF1CDBY5pXIaumQRoVJtqno.jpg"
    },
    {
      "known_for_department": "Acting",
      "id": 1547858,
      "name": "Bill Billions",
      "known_for": [
        {
          "release_date": "2015-12-11",
          "id": 367551,
          "vote_count": 100,
          "video": false,
          "media_type": "movie",
          "vote_average": 5.2,
          "title": "American Hero",
          "genre_ids": [
            28,
            35,
            878
          ],
          "original_title": "American Hero",
          "original_language": "en",
          "adult": false,
          "backdrop_path": "/xVqO8aah6HgLfP0bsG9YBidpNQJ.jpg",
          "overview": "Melvin, a reluctant hero who is far from super, has been suppressing his telekinetic powers for years with booze, drugs, and women. In the process, he has failed at practically everything, most of all as a parent to his son. After a brush with death, Melvin decides to use his powers for good and clean up the streets of New Orleans with the help of his best friend/definitely-not-a-sidekick, Lucille. For a man who can do the impossible, it might be a fight even he can’t win.",
          "poster_path": "/cbpv3Ocs772JVRLT6xlRJsiPwFp.jpg"
        },
        {
          "release_date": "2018-03-24",
          "id": 513510,
          "vote_count": 14,
          "video": false,
          "media_type": "movie",
          "vote_average": 5.7,
          "title": "All Light Will End",
          "genre_ids": [
            27,
            53
          ],
          "original_title": "All Light Will End",
          "original_language": "en",
          "adult": false,
          "backdrop_path": "/2uvfioN7TjQCSlLmRFedRCya2Hd.jpg",
          "overview": "When a capricious young author with a dark secret returns home for her brother's graduation, she finds herself haunted by the past and tormented by night terrors.",
          "poster_path": "/OiReATeSgIyIPePtNeaUfQfDGX.jpg"
        },
        {
          "poster_path": "/tnxNqC3S9qgyx4PdwT1MybcpCYJ.jpg",
          "id": 554979,
          "vote_count": 8,
          "video": false,
          "media_type": "movie",
          "adult": false,
          "backdrop_path": "/mFCR7qscnhseuGXbE0v2afvr0wH.jpg",
          "genre_ids": [
            18,
            10751,
            878
          ],
          "original_title": "Mail Order Monster",
          "original_language": "en",
          "title": "Mail Order Monster",
          "vote_average": 5,
          "overview": "A girl seeks help and guidance from a robot monster to cope with the bullies at school and her father's new girlfriend.",
          "release_date": "2018-11-06"
        }
      ],
      "popularity": 0.6,
      "profile_path": null,
      "gender": 0,
      "media_type": "person",
      "adult": false
    },
    {
      "known_for_department": "Production",
      "id": 2285018,
      "name": "Ayoka Billions",
      "known_for": [
        {
          "release_date": "2019-09-27",
          "id": 565383,
          "vote_count": 15,
          "video": false,
          "media_type": "movie",
          "vote_average": 6.1,
          "title": "The Death of Dick Long",
          "genre_ids": [
            35,
            80,
            18
          ],
          "original_title": "The Death of Dick Long",
          "original_language": "en",
          "adult": false,
          "backdrop_path": "/gTNCO9iTeOq9m4pyUZwNoMCvdGf.jpg",
          "overview": "Dick died last night, and Zeke and Earl don’t want anybody finding out how. That’s too bad though, cause news travels fast in small-town Alabama.",
          "poster_path": "/vURitOcmtcH8Dr1bWryTvfkeyJX.jpg"
        }
      ],
      "popularity": 0.6,
      "profile_path": null,
      "gender": 0,
      "media_type": "person",
      "adult": false
    },
    {
      "vote_count": 0,
      "popularity": 0.6,
      "id": 238821,
      "video": false,
      "media_type": "movie",
      "vote_average": 0,
      "title": "Thousands... Not Billions",
      "release_date": "2005-01-01",
      "original_language": "en",
      "original_title": "Thousands... Not Billions",
      "genre_ids": [
        99
      ],
      "backdrop_path": null,
      "adult": false,
      "overview": "Radiometric dating is one of the linchpins of evolutionary education today. Dr. Don DeYoung shatters this and other dating methods employed by evolutionists to cast doubt on the reliability of the Bible and its chronology of earth history. Evolutionists seek to undermine faith in Genesis as the true documentary of the history of the universe. When people are told that a dinosaur bone has been determined to be tens of millions of years old, that obviously doesn’t square with the biblical record of man being created on Day 6 with the land animals. But DeYoung now demonstrates that Christians no longer have to puzzle over this glaring contradiction.",
      "poster_path": "/qn15fLI8x90BBag3Q4E0NJSDrsp.jpg"
    },
    {
      "poster_path": "/hM4rIzzRZ7CifI46JgaY6pL9lP2.jpg",
      "popularity": 1.001,
      "vote_count": 0,
      "video": false,
      "media_type": "movie",
      "id": 612537,
      "adult": false,
      "backdrop_path": null,
      "original_language": "en",
      "original_title": "From Bedrooms to Billions: The PlayStation Revolution",
      "genre_ids": [
        99
      ],
      "title": "From Bedrooms to Billions: The PlayStation Revolution",
      "vote_average": 0,
      "overview": "Feature film focusing on how the Sony PlayStation took Video Gaming to a whole new level for Gamers and Developers!",
      "release_date": "2019-09-01"
    },
    {
      "original_name": "The Foods that Make Billions",
      "id": 38601,
      "media_type": "tv",
      "name": "The Foods that Make Billions",
      "popularity": 0.6,
      "vote_count": 0,
      "vote_average": 0,
      "first_air_date": "2010-11-23",
      "poster_path": null,
      "genre_ids": [],
      "original_language": "en",
      "backdrop_path": null,
      "overview": "A documentary series which tells the story of how big business feeds us by transforming simple commodities into everyday necessities and highly profitable brands",
      "origin_country": [
        "GB"
      ]
    },
    {
      "vote_count": 0,
      "popularity": 0.6,
      "id": 395824,
      "video": false,
      "media_type": "movie",
      "vote_average": 0,
      "title": "From Billions to None: The Passenger Pigeon's Flight to Extinction",
      "release_date": "2014-09-01",
      "original_language": "en",
      "original_title": "From Billions to None: The Passenger Pigeon's Flight to Extinction",
      "genre_ids": [],
      "backdrop_path": null,
      "adult": false,
      "overview": "From Billions to None follows naturalist and author Joel Greenberg and his friends on a quest to reveal the incredible, mostly forgotten story of how the passenger pigeon, the most abundant bird species in North America for thousands of years, became extinct by human hands in a geologic heartbeat. From Billions to None retells the remarkable story of the passenger pigeon and explores its striking relevance to conservation challenges today, and plans for its possible revival. Interweaving rare archival material, CGI animation that brings the flocks of millions to life and aerial cinematography, the film recreates the awe-inspiring nature of these birds, and presents passionate scientists, teachers and young people who reveal why, 100 years later, it's important to remember the event - and act.",
      "poster_path": "/xGjOGXoLtBPhZdfzmoZEeKIAMiA.jpg"
    },
    {
      "poster_path": "/vH7s14m6trJhdteH4rbEJxzzGoR.jpg",
      "popularity": 0.6,
      "vote_count": 0,
      "video": false,
      "media_type": "movie",
      "id": 488790,
      "adult": false,
      "backdrop_path": "/3aV4z6c7zcla8sVepUIXFqa65i.jpg",
      "original_language": "en",
      "original_title": "Jay Billion's Anything But Love",
      "genre_ids": [
        35
      ],
      "title": "Jay Billion's Anything But Love",
      "vote_average": 0,
      "overview": "Two divorcees are jaded on love. They meet each other and have to figure how to let their guard down.",
      "release_date": "2013-12-04"
    },
    {
      "known_for_department": "Acting",
      "id": 1381030,
      "name": "Maki Billiones",
      "known_for": [
        {
          "vote_count": 2,
          "video": false,
          "media_type": "movie",
          "id": 63897,
          "adult": false,
          "genre_ids": [
            35,
            10749
          ],
          "original_title": "Who's That Girl?",
          "original_language": "tl",
          "title": "Who's That Girl?",
          "vote_average": 4.3,
          "overview": "Elizabeth Pedroza (Curtis) is a UST Architecture graduate infatuated with her long-time school crush, John Eduque (Luis Manzano). Her world comes crushing down when she learns about the death of Eduque. She immediately goes to the wake and gets the shock of her life. She sees an older man, instead of a young man, lying in the coffin. The wife of the deceased John Eduque Sr gets piqued with her visit. A family friend’s simple question ‘who’s that girl?’ soon escalates into a grand-scale inquisition complete with kidnapping and high-profile rescue.",
          "release_date": "2011-03-02"
        }
      ],
      "popularity": 0.6,
      "profile_path": null,
      "gender": 0,
      "media_type": "person",
      "adult": false
    },
    {
      "known_for_department": "Acting",
      "id": 1083881,
      "name": "Cheska Billiones",
      "known_for": [
        {
          "vote_count": 3,
          "video": false,
          "media_type": "movie",
          "adult": false,
          "vote_average": 6,
          "title": "The Adventures of Pureza - Queen Of The Riles",
          "original_language": "tl",
          "original_title": "The Adventures of Pureza - Queen Of The Riles",
          "genre_ids": [
            35
          ],
          "id": 73086,
          "backdrop_path": "/og7bD3t0yIeSQX1WpBZdV7UOR4N.jpg",
          "overview": "The story revolves with Pura, (Melai) who plays the comedic role of a bubbly, caring, kind-hearted, very hardworking “dakilang ate” who wants nothing but only the best for her one and only beloved brother, Ulam, and uplift their dismal life. In all her endeavors, Pura’s best friend, Ruben (Jason Francisco), has always been by her side. Pura and Ruben then stumbles into a one-time big time opportunity to usher a Brazilian model who manages to escape them. With this unfortunate turn of event, Pura steps into the role … literally. She is now the model Pureza Mayriles! Basking in the promise of a better fortune plus a serendipitous love, little did Pura know that she has dragged herself into a life-threatening mess? Now running for their lives, Pura and Ruben has to detangle themselves from the dangers that faces them and how! Read More: The Adventures of Pureza: Queen of The Riles Trailer | Pinoymovieblog.com Under Creative Commons License: Attribution Share Alike",
          "release_date": "2011-07-13"
        },
        {
          "release_date": "2008-05-28",
          "id": 50720,
          "vote_count": 3,
          "video": false,
          "media_type": "movie",
          "vote_average": 6.3,
          "title": "Caregiver",
          "genre_ids": [
            18
          ],
          "original_title": "Caregiver",
          "original_language": "en",
          "adult": false,
          "backdrop_path": "/bvwGldHNcsobXJyjaScBcSJePx3.jpg",
          "overview": "A grade school English teacher Sarah Gonzales joins the 150,000 Pinoy OFWs working in the United Kingdom to support her Husband, Teddy Gonzales in making a better living for their family. More than just a chronicle of the Filipinos experience working as nurses and caregivers in the UK, this story also charts Sarah's journey to self-discovery from a submissive wife who makes sacrifices for her Husband; Teddy's aspirations to an empowered woman who finds dignity and pride in a humbling job as a Caregiver in London.",
          "poster_path": "/vwBeNAlTXFl1Zedb33U5YBigm7k.jpg"
        },
        {
          "vote_count": 2,
          "video": false,
          "media_type": "movie",
          "id": 127074,
          "vote_average": 8.3,
          "original_language": "en",
          "original_title": "My Kuya's Wedding",
          "title": "My Kuya's Wedding",
          "genre_ids": [
            18,
            10749
          ],
          "adult": false,
          "overview": "Inseparable as siblings, Jeff  and Kat grew up very close to each other through thick and thin. Kat being overzealous and very wary of girls who likes her brother Jeff. Her Kuya simply means the world to her.  Years later, Kat is all grown-up and lovely, and soon awaits her Kuyas return after four years of hard work from abroad. But all this excitement of a sibling reunion is foiled at the airport upon sight of Heidi, Kats worst nightmare and her brothers fiancée.  Fueled with envy, Kat embarks on an all-out scheme to pull out all the stops to their impending wedding with the help of her gay bestfriend of all seasons. However, as Kat schemes to freeze the marital icing off her siblings cake, she finds herself falling for the charms of an evicted reality show superstar - Aris  who happens to be Heidis brother.  As she desperately clings to her last semblance of family, her Kuya Jeff, will Kat be able to stop this bridezilla from snatching away her only Kuya in her life?",
          "release_date": "2007-08-29"
        }
      ],
      "popularity": 0.6,
      "profile_path": null,
      "gender": 0,
      "media_type": "person",
      "adult": false
    },
    {
      "poster_path": "/pTFv3fksOhUHkSLeWiY7hzowSq6.jpg",
      "popularity": 3.235,
      "vote_count": 31,
      "video": false,
      "media_type": "movie",
      "id": 35201,
      "adult": false,
      "backdrop_path": "/6tPw2MyxnPYLxKXIK4UCQSw0fWx.jpg",
      "original_language": "en",
      "original_title": "The Holcroft Covenant",
      "genre_ids": [
        28,
        53
      ],
      "title": "The Holcroft Covenant",
      "vote_average": 5.2,
      "overview": "A man who was a confidant of Adolf Hitler dies and leaves a fortune to make amends for his Nazi past--but his son has to search the world to find it",
      "release_date": "1985-09-20"
    }
  ]
}

Одна из моделей, модель MovieResults.

struct MovieResults: Codable {

    let page: Int
    let results: [Movie]
    let totalPages: Int
    let totalResults: Int

    enum CodingKeys: String, CodingKey {
        case page
        case results
        case totalPages = "total_pages"
        case totalResults = "total_results"
    }
}

/// Mov ie модель

struct Movie: Codable, Equatable {

    let posterPath: String?
    let adult: Bool
    let overview: String
    let releaseDate: String
    let genreIds: [Int]
    let id: Int
    let originalTitle: String
    let originalLanguage: String
    let title: String
    let backdropPath: String?
    let popularity: Double
    let voteCount: Int
    let video: Bool
    let voteAverage: Double

    var releaseYear: String {
        return String(releaseDate.prefix(4))
    }

    enum CodingKeys: String, CodingKey {
        case posterPath = "poster_path"
        case adult
        case overview
        case releaseDate = "release_date"
        case genreIds = "genre_ids"
        case id
        case originalTitle = "original_title"
        case originalLanguage = "original_language"
        case title
        case backdropPath = "backdrop_path"
        case popularity
        case voteCount = "vote_count"
        case video
        case voteAverage = "vote_average"
    }
}

1 Ответ

0 голосов
/ 19 февраля 2020

Просто создайте основную модель:

 public class MainClas{
      public ChildOne ChildOnes { get; set; }
      public ChildTwo ChildTwos { get; set; }
      public ChildThree ChildThress { get; set; }
 }
...