尝试反序列化 TheMovieDB JSON

Trying to deserialize TheMovieDB JSON

我正在从 TheMovieDB 访问 API 并检索 JSON,其中包含如下信息:

我想将此 JSON 反序列化为模型集合。我有一个电视节目实例的模型,定义如下:

class SeriesModel : BindableBase
{
    public SeriesModel(){}

    #region Properties

    private string _backdropPath;
    public string Backdrop_Path
    {
        get { return _backdropPath; }
        set { this.SetProperty(ref this._backdropPath, value); }
    }

    private string _firstAirDate;
    public string First_Air_Date
    {
        get { return _firstAirDate; }
        set { this.SetProperty(ref this._firstAirDate, value); }
    }

    private int[] _genreIDs;
    public int[] Genre_IDs
    {
        get { return _genreIDs; }
        set { this.SetProperty(ref this._genreIDs, value); }
    }

    private int _id;
    public int ID
    {
        get { return _id; }
        set { this.SetProperty(ref this._id, value); }
    }

    private string _originalLanguage;
    public string OriginalLanguage
    {
        get { return _originalLanguage; }
        set { this.SetProperty(ref this._originalLanguage, value); }
    }

    private string _originalName;
    public string Original_Name
    {
        get { return _originalName; }
        set { this.SetProperty(ref this._originalName, value); }
    }

    private string _overview;
    public string Overview
    {
        get { return _overview; }
        set { this.SetProperty(ref this._overview, value); }
    }

    private string _originCountry;
    public string Origin_Country
    {
        get { return _originCountry; }
        set { this.SetProperty(ref this._originCountry, value); }
    }

    private string _posterPath;
    public string Poster_Path
    {
        get { return _posterPath; }
        set { this.SetProperty(ref this._posterPath, value); }
    }

    private string _popularity;
    public string Popularity
    {
        get { return _popularity; }
        set { this.SetProperty(ref this._popularity, value); }
    }

    private string _name;
    public string Name
    {
        get { return _name; }
        set { this.SetProperty(ref this._name, value); }
    }

    private string _voteAverage;
    public string Vote_Average
    {
        get { return _voteAverage; }
        set { this.SetProperty(ref this._voteAverage, value); }
    }

    private int _voteCount;

    public int Vote_Count
    {
        get { return _voteCount; }
        set { this.SetProperty(ref this._voteCount, value); }
    }

    #endregion
}

我正在使用 Newtonsoft JSON 通过以下代码对其进行反序列化:

    public async static void GetPopularSeriesCollection()
    {
        ObservableCollection<SeriesModel> seriesCollection = new ObservableCollection<SeriesModel>();
        var popularJson = await ApiHandler.GetPopularSeriesJSON();
        seriesCollection = JsonConvert.DeserializeObject<ObservableCollection<SeriesModel>>(popularJson);
    }

第二行是调用下面的方法returns上图中显示的json字符串:

    const string apiKey = "hidden";
    static readonly Uri baseAddress = new Uri("http://api.themoviedb.org/3/");
    static readonly HttpClient httpClient = new HttpClient { BaseAddress = baseAddress };

    public static async Task<string> GetPopularSeriesJSON()
    {
        using (httpClient)
        {
            httpClient.DefaultRequestHeaders.TryAddWithoutValidation("accept", "application/json");

            using (var response = await httpClient.GetAsync("tv/popular?api_key=" + apiKey))
                return await response.Content.ReadAsStringAsync();
        }
    }

我在 JsonConvert.DeserializeObject<...

行收到以下错误

Additional information: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.ObjectModel.ObservableCollection`1[ProjectSirV.Models.SeriesModel]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly. To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.

这几乎是我第一次弄乱 JSON API 的东西,我不完全确定我所做的是否正确。非常感谢任何帮助。

编辑:请求的原始 JSON 字符串

{"page":1,"results":[{"backdrop_path":"/98MkbBwdbw9xfmxJlYlBWqu6xZZ.jpg","first_air_date":"2015-06-14","genre_ids":[18,878],"id":62822,"original_language":"en","original_name":"Humans","overview":"In a parallel present where the latest must-have gadget for any busy family is a 'Synth' - a highly-developed robotic servant that's so similar to a real human it's transforming the way we live.","origin_country":["GB","US"],"poster_path":"/gJCyS65ieDT827F2NR9Nx9ZLuw5.jpg","popularity":34.850585,"name":"Humans","vote_average":9.4,"vote_count":6},{"backdrop_path":"/aKz3lXU71wqdslC1IYRC3yHD6yw.jpg","first_air_date":"2011-04-17","genre_ids":[10765,18],"id":1399,"original_language":"en","original_name":"Game of Thrones","overview":"Seven noble families fight for control of the mythical land of Westeros. Friction between the houses leads to full-scale war. All while a very ancient evil awakens in the farthest north. Amidst the war, a neglected military order of misfits, the Night's Watch, is all that stands between the realms of men and icy horrors beyond.\n\n","origin_country":["US"],"poster_path":"/jIhL6mlT7AblhbHJgEoiBIOUVl1.jpg","popularity":28.002963,"name":"Game of Thrones","vote_average":9.0,"vote_count":285},{"backdrop_path":"/nGsNruW3W27V6r4gkyc3iiEGsKR.jpg","first_air_date":"2007-09-24","genre_ids":[35],"id":1418,"original_language":null,"original_name":"The Big Bang Theory","overview":"The Big Bang Theory is centered on five characters living in Pasadena, California: roommates Leonard Hofstadter and Sheldon Cooper; Penny, a waitress and aspiring actress who lives across the hall; and Leonard and Sheldon's equally geeky and socially awkward friends and co-workers, mechanical engineer Howard Wolowitz and astrophysicist Raj Koothrappali. The geekiness and intellect of the four guys is contrasted for comic effect with Penny's social skills and common sense.","origin_country":["US"],"poster_path":"/wQoosZYg9FqPrmI4zeCLRdEbqAB.jpg","popularity":20.511501,"name":"The Big Bang Theory","vote_average":8.0,"vote_count":191},{"backdrop_path":"/qDEIZWnyRxWTB9zCjyyj4mbURVp.jpg","first_air_date":"2014-01-12","genre_ids":[18],"id":46648,"original_language":null,"original_name":"True Detective","overview":"An American anthology police detective series utilizing multiple timelines in which investigations seem to unearth personal and professional secrets of those involved, both within or outside the law.","origin_country":["US"],"poster_path":"/yCw88GhkkV5UDDAQJOJ6kQSdvQY.jpg","popularity":19.251679,"name":"True Detective","vote_average":8.6,"vote_count":95},{"backdrop_path":"/ggWL016MsLIFAXq6q5wFQ85SKpe.jpg","first_air_date":"2015-06-30","genre_ids":[80,27,9648],"id":62823,"original_language":"en","original_name":"Scream","overview":"What starts as a YouTube video going viral, soon leads to problems for the teenagers of Lakewood and serves as the catalyst for a murder that opens up a window to the town's troubled past. Everyone has secrets. Everyone tells lies. Everyone is fair game.","origin_country":["US"],"poster_path":"/nPMlfwYoEBXku0jFnWlQI05exZL.jpg","popularity":19.567071,"name":"Scream","vote_average":8.0,"vote_count":1},{"backdrop_path":"/tPwpc9Uo1Fly50urDxfGWWk7H77.jpg","first_air_date":"2005-03-26","genre_ids":[28,12,18,878],"id":57243,"original_language":"en","original_name":"Doctor Who","overview":"The Doctor looks and seems human. He's handsome, witty, and could be mistaken for just another man in the street. But he is a Time Lord: a 900 year old alien with 2 hearts, part of a gifted civilization who mastered time travel. The Doctor saves planets for a living – more of a hobby actually, and he's very, very good at it. He's saved us from alien menaces and evil from before time began – but just who is he?","origin_country":["GB"],"poster_path":"/igDhbYQTvact1SbNDbzoeiFBGda.jpg","popularity":17.276125,"name":"Doctor Who","vote_average":8.4,"vote_count":80},{"backdrop_path":"/sCx2r2bw49OqxnjWaU9DsPwdR0C.jpg","first_air_date":"1994-09-22","genre_ids":[35],"id":1668,"original_language":"en","original_name":"Friends","overview":"Friends is an American sitcom created by David Crane and Marta Kauffman, which aired on NBC from September 22, 1994 to May 6, 2004. The series revolves around a group of friends in the New York City borough of Manhattan. The series was produced by Bright/Kauffman/Crane Productions, in association with Warner Bros. Television. The original executive producers were Crane, Kauffman, and Kevin S. Bright, with numerous others being promoted in later seasons.\n\nKauffman and Crane began developing Friends under the title Insomnia Cafe in November/December 1993. They presented the idea to Bright, with whom they had previously worked, and together they pitched a seven-page treatment of the series to NBC. After several script rewrites and changes, including a second title change to Friends Like Us, the series was finally named Friends and premiered on NBC's coveted Thursday 8:30 pm timeslot. Filming for the series took place at Warner Bros. Studios in Burbank, California in front of a live studio audience. The series finale, airing on May 6, 2004, was watched by 52.5 million American viewers, making it the fourth most watched series finale in television history and the most watched episode of the decade.","origin_country":["US"],"poster_path":"/7buCWBTpiPrCF5Lt023dSC60rgS.jpg","popularity":16.095621,"name":"Friends","vote_average":8.0,"vote_count":90},{"backdrop_path":"/rKuw94LmTWtCHC9Lm5LeiorGr9d.jpg","first_air_date":"2011-06-05","genre_ids":[10759,9648,10765,18],"id":34524,"original_language":"en","original_name":"Teen Wolf","overview":"Scott McCall, a high school student living in the town of Beacon Hills has his life drastically changed when he's bitten by a werewolf, becoming one himself. He must henceforth learn to balance his problematic new identity with his day-to-day teenage life. The following characters are instrumental to his struggle: Stiles, his best friend; Allison, his love interest who comes from a family of werewolf hunters; and Derek, a mysterious werewolf with a dark past. Throughout the series, he strives to keep his loved ones safe while maintaining normal relationships with them.","origin_country":["US"],"poster_path":"/wvU3ki9Qp7amrgX4PIYeo4YiX2O.jpg","popularity":15.945563,"name":"Teen Wolf","vote_average":7.6,"vote_count":31},{"backdrop_path":"/2MOwrNrqFbWRWIOVevQE16lzEkB.jpg","first_air_date":"2015-06-30","genre_ids":[18,53],"id":62517,"original_language":"en","original_name":"Zoo","overview":"Set amidst a wave of violent animal attacks sweeping across the planet, a young renegade scientist is thrust into a race to unlock the mystery behind this pandemic before time runs out for animals and humans alike.","origin_country":["US"],"poster_path":"/8blVYBMPzLDEIeWNGFbhofL9muj.jpg","popularity":14.718462,"name":"Zoo","vote_average":8.0,"vote_count":1},{"backdrop_path":"/kohPYEYHuQLWX3gjchmrWWOEycD.jpg","first_air_date":"2015-06-12","genre_ids":[878],"id":62425,"original_language":"en","original_name":"Dark Matter","overview":"The six-person crew of a derelict spaceship awakens from stasis in the farthest reaches of space. Their memories wiped clean, they have no recollection of who they are or how they got on board. The only clue to their identities is a cargo bay full of weaponry and a destination: a remote mining colony that is about to become a war zone. With no idea whose side they are on, they face a deadly decision. Will these amnesiacs turn their backs on history, or will their pasts catch up with them?","origin_country":["CA"],"poster_path":"/iDSXueb3hjerXMq5w92rBP16LWY.jpg","popularity":14.599907,"name":"Dark Matter","vote_average":6.5,"vote_count":8},{"backdrop_path":"/mmxxEpTqVdwBlu5Pii7tbedBkPC.jpg","first_air_date":"2014-10-07","genre_ids":[28,12,18,878],"id":60735,"original_language":"en","original_name":"The Flash","overview":"After a particle accelerator causes a freak storm, CSI Investigator Barry Allen is struck by lightning and falls into a coma. Months later he awakens with the power of super speed, granting him the ability to move through Central City like an unseen guardian angel. Though initially excited by his newfound powers, Barry is shocked to discover he is not the only \"meta-human\" who was created in the wake of the accelerator explosion -- and not everyone is using their new powers for good. Barry partners with S.T.A.R. Labs and dedicates his life to protect the innocent. For now, only a few close friends and associates know that Barry is literally the fastest man alive, but it won't be long before the world learns what Barry Allen has become...The Flash.","origin_country":["US"],"poster_path":"/9ZuWc3wWPDvWWterM0DlQxjhCBR.jpg","popularity":14.526461,"name":"The Flash","vote_average":8.1,"vote_count":83},{"backdrop_path":"/wfe7Xf7tc0zmnkoNyN3xor0xR8m.jpg","first_air_date":"2005-09-19","genre_ids":[35],"id":1100,"original_language":"en","original_name":"How I Met Your Mother","overview":"How I Met Your Mother is an American sitcom that premiered on CBS on September 19, 2005. The 2013–14 season will be the show's ninth and final season. The series follows the main character, Ted Mosby, and his group of friends in Manhattan. As a framing device, Ted, in the year 2030, recounts to his son and daughter the events that led to his meeting their mother.","origin_country":["US"],"poster_path":"/izncB6dCLV7LBQ5MsOPyMx9mUDa.jpg","popularity":14.508464,"name":"How I Met Your Mother","vote_average":7.9,"vote_count":93},{"backdrop_path":"/lnnrirKFGwFW18GiH3AmuYy40cz.jpg","first_air_date":"1989-12-16","genre_ids":[16,35,10751],"id":456,"original_language":"en","original_name":"The Simpsons","overview":"The Simpsons is an American animated sitcom created by Matt Groening for the Fox Broadcasting Company. The series is a satirical parody of a middle class American lifestyle epitomized by its family of the same name, which consists of Homer, Marge, Bart, Lisa, and Maggie. The show is set in the fictional town of Springfield and parodies American culture, society, television, and many aspects of the human condition.","origin_country":["US"],"poster_path":"/yTZQkSsxUFJZJe67IenRM0AEklc.jpg","popularity":13.027592,"name":"The Simpsons","vote_average":8.6,"vote_count":98},{"backdrop_path":"/trypBo0ldWAZ4ULeQDjkzzW7To3.jpg","first_air_date":"2010-06-08","genre_ids":[9648,18],"id":31917,"original_language":"en","original_name":"Pretty Little Liars","overview":"Based on the Pretty Little Liars series of young adult novels by Sara Shepard, the series follows the lives of four girls — Spencer, Hanna, Aria, and Emily — whose clique falls apart after the disappearance of their queen bee, Alison. One year later, they begin receiving messages from someone using the name \"A\" who threatens to expose their secrets — including long-hidden ones they thought only Alison knew. ","origin_country":["US"],"poster_path":"/2rOLNdUPahiAq6VuoA1I6sA45cs.jpg","popularity":13.890999,"name":"Pretty Little Liars","vote_average":6.8,"vote_count":27},{"backdrop_path":"/tacmO3UpPX26bb1EQz8c11lQezR.jpg","first_air_date":"2015-06-16","genre_ids":[35],"id":62771,"original_language":"en","original_name":"Clipped","overview":"Clipped centers on a group of barbershop coworkers who all went to high school together but ran in very different crowds. Now they find themselves working together at Buzzy's, a barbershop in Charlestown, Massachusetts.","origin_country":["US"],"poster_path":"/a7Tp2hVM3aMINT9L5blINV6AweY.jpg","popularity":13.621536,"name":"Clipped","vote_average":2.8,"vote_count":3},{"backdrop_path":"/ji6ehQWPo00KScXhdmub8wQA6H.jpg","first_air_date":"2005-09-13","genre_ids":[18,9648,10765],"id":1622,"original_language":"en","original_name":"Supernatural","overview":"When they were boys, Sam and Dean Winchester lost their mother to a mysterious and demonic supernatural force. Subsequently, their father raised them to be soldiers. He taught them about the paranormal evil that lives in the dark corners and on the back roads of America ... and he taught them how to kill it. Now, the Winchester brothers crisscross the country in their '67 Chevy Impala, battling every kind of supernatural threat they encounter along the way. ","origin_country":["US"],"poster_path":"/3iFm6Kz7iYoFaEcj4fLyZHAmTQA.jpg","popularity":12.408955,"name":"Supernatural","vote_average":8.1,"vote_count":65},{"backdrop_path":"/zYFQM9G5j9cRsMNMuZAX64nmUMf.jpg","first_air_date":"2010-10-31","genre_ids":[18,27,53],"id":1402,"original_language":"en","original_name":"The Walking Dead","overview":"The Walking Dead is an American horror drama television series developed by Frank Darabont. It is based on the comic book series of the same name by Robert Kirkman, Tony Moore, and Charlie Adlard. The series stars Andrew Lincoln as sheriff's deputy Rick Grimes, who 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.","origin_country":["US"],"poster_path":"/vxuoMW6YBt6UsxvMfRNwRl9LtWS.jpg","popularity":12.185327,"name":"The Walking Dead","vote_average":7.9,"vote_count":167},{"backdrop_path":"/eSzpy96DwBujGFj0xMbXBcGcfxX.jpg","first_air_date":"2008-01-19","genre_ids":[18],"id":1396,"original_language":null,"original_name":"Breaking Bad","overview":"Breaking Bad is an American crime drama television series created and produced by Vince Gilligan. Set and produced in Albuquerque, New Mexico, Breaking Bad is the story of Walter White, a struggling high school chemistry teacher who is diagnosed with inoperable lung cancer at the beginning of the series. He turns to a life of crime, producing and selling methamphetamine, in order to secure his family's financial future before he dies, teaming with his former student, Jesse Pinkman. Heavily serialized, the series is known for positioning its characters in seemingly inextricable corners and has been labeled a contemporary western by its creator.","origin_country":["US"],"poster_path":"/4yMXf3DW6oCL0lVPZaZM2GypgwE.jpg","popularity":11.959898,"name":"Breaking Bad","vote_average":8.9,"vote_count":254},{"backdrop_path":"/9OEWK8nMTFmqQwAFpFyn7snIGP8.jpg","first_air_date":"2015-05-27","genre_ids":[18,80],"id":62560,"original_language":"en","original_name":"Mr. Robot","overview":"A contemporary and culturally resonant drama about a young programmer, Elliot, who suffers from a debilitating anti-social disorder and decides that he can only connect to people by hacking them. He wields his skills as a weapon to protect the people that he cares about. Elliot will find himself in the intersection between a cybersecurity firm he works for and the underworld organizations that are recruiting him to bring down corporate America.","origin_country":["US"],"poster_path":"/aubGV7NnVPjmX0XuXpHRlA1i5qF.jpg","popularity":12.787437,"name":"Mr. Robot","vote_average":7.8,"vote_count":8},{"backdrop_path":"/g3Cke7hDiIq80HFv6agwxTx8AfT.jpg","first_air_date":"2009-09-23","genre_ids":[35,10751],"id":1421,"original_language":null,"original_name":"Modern Family","overview":"Modern Family is an American comedy series which debuted on ABC on September 23, 2009. Presented in mockumentary style, the fictional characters frequently talk directly into the camera. The program tells of Jay Pritchett, his second wife, their infant son and his stepson, and his two children and their families. Christopher Lloyd and Steven Levitan conceived the series while sharing stories of their own \"modern families\".","origin_country":["US"],"poster_path":"/vmokjFmPtDZySnNTQd6uqYcTjNF.jpg","popularity":11.451724,"name":"Modern Family","vote_average":8.3,"vote_count":55}],"total_pages":3093,"total_results":61856}

您要反序列化的集合不在根级别,它在 "results" 属性:

seriesCollection = JObject.Parse(popularJson)["results"]
    .ToObject<ObservableCollection<SeriesModel>>();