Xamarin形式。无法在列表中显示json对象

时间:2018-07-01 17:02:49

标签: json listview object xamarin.forms

我完全是xamarin形式的。我正在尝试制作一个使用TMDB api来显示电影列表的应用程序,但出现此异常:

  

Newtonsoft.Json.JsonSerializationException:无法将当前JSON对象(例如{“ name”:“ value”})反序列化为类型'System.Collections.Generic.List`1 [CinemaApp.Models.NowPlaying]',因为该类型需要JSON数组(例如[1,2,3])才能正确反序列化。

这是我的xaml文件

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         x:Class="CinemaApp.PlayingNowPage">
<ContentPage.Content>
    <AbsoluteLayout HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">

        <StackLayout x:Name="SLMovies" AbsoluteLayout.LayoutFlags="All"
                     AbsoluteLayout.LayoutBounds="0,0,1,1">

            <ListView x:Name="MoviesListView"
                      HasUnevenRows="True"
                      SeparatorVisibility="None">
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <ViewCell>
                            <Frame>
                                <Grid>
                                    <Grid.ColumnDefinitions>
                                        <ColumnDefinition Width="0.4*"/>
                                        <ColumnDefinition Width="*"/>
                                    </Grid.ColumnDefinitions>

                                    <Image Source="{Binding full_poster_path}" Grid.Column="0"
                                           HeightRequest="120"
                                           WidthRequest="150"/>
                                    <StackLayout Grid.Column="1">
                                        <Label Text="{Binding title}"
                                               TextColor="#E91E63" 
                                               FontAttributes="Bold"/>
                                        <Label Text="{Binding vote_average}"/>
                                        <Label Text="{Binding release_date}"> 
</Label>
                                        <StackLayout 
                                            Orientation="Horizontal"
                                            HorizontalOptions="FillAndExpand">
                                            <Label HorizontalOptions="EndAndExpand"
                                                   Text="{Binding Duration}"> 
 </Label>
                                        </StackLayout>
                                    </StackLayout>
                                </Grid>
                            </Frame>
                        </ViewCell>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>
        </StackLayout>

        <StackLayout
            x:Name="SLLoader"
            IsVisible="True"
            Padding="12"
            AbsoluteLayout.LayoutFlags="PositionProportional"
            AbsoluteLayout.LayoutBounds="0.5,0.5,-1,-1">

            <ActivityIndicator 
                IsRunning="True"
                Color="#00000000"/>
            <Label 
                Text="Loading..."
                HorizontalOptions="Center"
                TextColor="Red"/>
        </StackLayout>
    </AbsoluteLayout>
</ContentPage.Content>
</ContentPage>

这是对象的类

using System;
using System.Collections.Generic;
using System.Text;

namespace CinemaApp.Models
{
public class NowPlaying
{
    public int id { get; set; }
    public bool video { get; set; }
    public double vote_average { get; set; }
    public string title { get; set; }
    public string poster_path { get; set; }
    public string original_title { get; set; }
    public string release_date { get; set; }

    public string full_poster_path
    {
        get
        {
            if (string.IsNullOrEmpty(poster_path))
            {
                return string.Empty;
            }

            return string.Format("https://image.tmdb.org/t/p/w185/" + 
poster_path);
        }
    }
}


}

这是主要类别:

namespace CinemaApp
    {
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class PlayingNowPage : ContentPage
    {
        public PlayingNowPage ()
        {
            InitializeComponent ();
            GetMovies();
        }

        private async void GetMovies()
        {
            try
            {
                SLLoader.IsVisible = true;
                HttpClient client = new HttpClient();
                var response = await client.GetStringAsync(                  
                 "https://api.themoviedb.org/3/movie/now_playing? 
                  api_key=XXXX&language=en-US&page=1");

                var movies = JsonConvert.DeserializeObject<List<NowPlaying>> 
               (response);


                Console.WriteLine("rere   "+movies);

                MoviesListView.ItemsSource = movies;
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: " + e);
            }
            finally
            {
                SLLoader.IsVisible = false;
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您的NowPlaying模型在一个正在播放的结果中仅包含对象的数据。如果您查看响应,例如网站上的示例:https://developers.themoviedb.org/3/movies/get-now-playing

{
  "page": 1,
  "results": [
    {
      "poster_path": "/e1mjopzAS2KNsvpbpahQ1a6SkSn.jpg",
      "adult": false,
      "overview": "From DC Comics comes the Suicide Squad, an antihero team of incarcerated supervillains who act as deniable assets for the United States government, undertaking high-risk black ops missions in exchange for commuted prison sentences.",
      "release_date": "2016-08-03",
      "genre_ids": [
        14,
        28,
        80
      ],
      "id": 297761,
      "original_title": "Suicide Squad",
      "original_language": "en",
      "title": "Suicide Squad",
      "backdrop_path": "/ndlQ2Cuc3cjTL7lTynw6I4boP4S.jpg",
      "popularity": 48.261451,
      "vote_count": 1466,
      "video": false,
      "vote_average": 5.91
    },
    {
      "poster_path": "/lFSSLTlFozwpaGlO31OoUeirBgQ.jpg",
      "adult": false,
      "overview": "The most dangerous former operative of the CIA is drawn out of hiding to uncover hidden truths about his past.",
      "release_date": "2016-07-27",
      "genre_ids": [
        28,
        53
      ],
      "id": 324668,
      "original_title": "Jason Bourne",
      "original_language": "en",
      "title": "Jason Bourne",
      "backdrop_path": "/AoT2YrJUJlg5vKE3iMOLvHlTd3m.jpg",
      "popularity": 30.690177,
      "vote_count": 649,
      "video": false,
      "vote_average": 5.25
    },
    {
      "poster_path": "/tgfRDJs5PFW20Aoh1orEzuxW8cN.jpg",
      "adult": false,
      "overview": "Arthur Bishop thought he had put his murderous past behind him when his most formidable foe kidnaps the love of his life. Now he is forced to travel the globe to complete three impossible assassinations, and do what he does best, make them look like accidents.",
      "release_date": "2016-08-25",
      "genre_ids": [
        80,
        28,
        53
      ],
      "id": 278924,
      "original_title": "Mechanic: Resurrection",
      "original_language": "en",
      "title": "Mechanic: Resurrection",
      "backdrop_path": "/3oRHlbxMLBXHfMqUsx1emwqiuQ3.jpg",
      "popularity": 20.375179,
      "vote_count": 119,
      "video": false,
      "vote_average": 4.59
    },
    {
      "poster_path": "/3ioyAtm0wXDyPy330Y7mJAJEHpU.jpg",
      "adult": false,
      "overview": "A high school senior finds herself immersed in an online game of truth or dare, where her every move starts to be manipulated by an anonymous community of \"watchers.\"",
      "release_date": "2016-07-27",
      "genre_ids": [
        18,
        53
      ],
      "id": 328387,
      "original_title": "Nerve",
      "original_language": "en",
      "title": "Nerve",
      "backdrop_path": "/a0wohltYr7Tzkgg2X6QKBe3txj1.jpg",
      "popularity": 7.17729,
      "vote_count": 86,
      "video": false,
      "vote_average": 6.84
    },
    {
      "poster_path": "/3S7V2Jd2G61LltoCsYUj4GwON5p.jpg",
      "adult": false,
      "overview": "A woman with a seemingly perfect life - a great marriage, overachieving kids, beautiful home, stunning looks and still holding down a career. However she's over-worked, over committed and exhausted to the point that she's about to snap. Fed up, she joins forces with two other over-stressed moms and all go on a quest to liberate themselves from conventional responsibilities, going on a wild un-mom like binge of freedom, fun and self-indulgence - putting them on a collision course with PTA Queen Bee Gwendolyn and her clique of devoted perfect moms.",
      "release_date": "2016-07-28",
      "genre_ids": [
        35
      ],
      "id": 376659,
      "original_title": "Bad Moms",
      "original_language": "en",
      "title": "Bad Moms",
      "backdrop_path": "/l9aqTBdafSo0n7u0Azuqo01YVIC.jpg",
      "popularity": 6.450367,
      "vote_count": 107,
      "video": false,
      "vote_average": 5.49
    },
    {
      "poster_path": "/sRxazAAodkAWVPJighRAsls2zCo.jpg",
      "adult": false,
      "overview": "A falsely accused nobleman survives years of slavery to take vengeance on his best friend who betrayed him.",
      "release_date": "2016-08-17",
      "genre_ids": [
        12,
        36,
        18
      ],
      "id": 271969,
      "original_title": "Ben-Hur",
      "original_language": "en",
      "title": "Ben-Hur",
      "backdrop_path": "/A4xbEpe9LevQCdvaNC0z6r8AfYk.jpg",
      "popularity": 6.379067,
      "vote_count": 60,
      "video": false,
      "vote_average": 3.83
    },
    {
      "poster_path": "/aRRLpsusORQxOpFkZvXdk00TkoY.jpg",
      "adult": false,
      "overview": "Nate Foster, a young, idealistic FBI agent, goes undercover to take down a radical white supremacy terrorist group. The bright up-and-coming analyst must confront the challenge of sticking to a new identity while maintaining his real principles as he navigates the dangerous underworld of white supremacy. Inspired by real events.",
      "release_date": "2016-08-19",
      "genre_ids": [
        80,
        18,
        53
      ],
      "id": 374617,
      "original_title": "Imperium",
      "original_language": "en",
      "title": "Imperium",
      "backdrop_path": "/9dMvJJ0eTVetq3kLwUXcphsY5H.jpg",
      "popularity": 5.855316,
      "vote_count": 33,
      "video": false,
      "vote_average": 6.05
    },
    {
      "poster_path": "/4pUIQO6OqbzxrFLGMDf2dlplSR9.jpg",
      "adult": false,
      "overview": "Southside With You chronicles a single day in the summer of 1989 when the future president of the United States, Barack Obama, wooed his future First Lady on an epic first date across Chicago's South Side.",
      "release_date": "2016-08-26",
      "genre_ids": [
        10749,
        18
      ],
      "id": 310888,
      "original_title": "Southside With You",
      "original_language": "en",
      "title": "Southside With You",
      "backdrop_path": "/fukREcpoPugi0yx6cVrFvsR7JBE.jpg",
      "popularity": 5.229414,
      "vote_count": 13,
      "video": false,
      "vote_average": 3.12
    },
    {
      "poster_path": "/wJXku1YhMKeuzYNEHux7XtaYPsE.jpg",
      "adult": false,
      "overview": "Based on a true story, “War Dogs” follows two friends in their early 20s living in Miami during the first Iraq War who exploit a little-known government initiative that allows small businesses to bid on U.S. Military contracts. Starting small, they begin raking in big money and are living the high life. But the pair gets in over their heads when they land a 300 million dollar deal to arm the Afghan Military—a deal that puts them in business with some very shady people, not the least of which turns out to be the U.S. Government.",
      "release_date": "2016-08-18",
      "genre_ids": [
        10752,
        35,
        18
      ],
      "id": 308266,
      "original_title": "War Dogs",
      "original_language": "en",
      "title": "War Dogs",
      "backdrop_path": "/2cLndRZy8e3das3vVaK3BdJfRIi.jpg",
      "popularity": 5.186717,
      "vote_count": 55,
      "video": false,
      "vote_average": 5.08
    },
    {
      "poster_path": "/e9Rzr8Hhu3pqdJtdDLC52PerLk1.jpg",
      "adult": false,
      "overview": "Pete is a mysterious 10-year-old with no family and no home who claims to live in the woods with a giant, green dragon named Elliott. With the help of Natalie, an 11-year-old girl whose father Jack owns the local lumber mill, forest ranger Grace sets out to determine where Pete came from, where he belongs, and the truth about this dragon.",
      "release_date": "2016-08-10",
      "genre_ids": [
        12,
        10751,
        14
      ],
      "id": 294272,
      "original_title": "Pete's Dragon",
      "original_language": "en",
      "title": "Pete's Dragon",
      "backdrop_path": "/AaRhHX0Jfpju0O6hNzScPRgX9Mm.jpg",
      "popularity": 4.93384,
      "vote_count": 72,
      "video": false,
      "vote_average": 4.85
    },
    {
      "poster_path": "/pXqnqw4V1Rly2HEacfl07d5DcUE.jpg",
      "adult": false,
      "overview": "59 year-old Ove is the block’s grumpy man. Several years ago he was deposed as president of the condominium association, but he could not give a damn about being deposed and therefore keeps looking over the neighborhood with an iron fist. When pregnant Parvaneh and her family move into the terraced house opposite Ove and accidentally back into Ove’s mailbox it sets off the beginning of an unexpected change in his life.",
      "release_date": "2016-08-26",
      "genre_ids": [
        35,
        18
      ],
      "id": 348678,
      "original_title": "En man som heter Ove",
      "original_language": "sv",
      "title": "A Man Called Ove",
      "backdrop_path": "/o3PDMTyyMOGFNtze7YsfdWeMKpm.jpg",
      "popularity": 4.790786,
      "vote_count": 27,
      "video": false,
      "vote_average": 5.57
    },
    {
      "poster_path": "/3Kr9CIIMcXTPlm6cdZ9y3QTe4Y7.jpg",
      "adult": false,
      "overview": "In the epic fantasy, scruffy, kindhearted Kubo ekes out a humble living while devotedly caring for his mother in their sleepy shoreside village. It is a quiet existence – until a spirit from the past catches up with him to enforce an age-old vendetta. Suddenly on the run from gods and monsters, Kubo’s chance for survival rests on finding the magical suit of armor once worn by his fallen father, the greatest samurai the world has ever known. Summoning courage, Kubo embarks on a thrilling odyssey as he faces his family’s history, navigates the elements, and bravely fights for the earth and the stars.",
      "release_date": "2016-08-18",
      "genre_ids": [
        12,
        16,
        14,
        10751
      ],
      "id": 313297,
      "original_title": "Kubo and the Two Strings",
      "original_language": "en",
      "title": "Kubo and the Two Strings",
      "backdrop_path": "/akd0Z0OiR20btITvmvweDcJ3m8H.jpg",
      "popularity": 4.572192,
      "vote_count": 34,
      "video": false,
      "vote_average": 6.93
    },
    {
      "poster_path": "/rxXA5vwJElXQ8BgrB0pocUcuqFA.jpg",
      "adult": false,
      "overview": "When Rebecca left home, she thought she left her childhood fears behind. Growing up, she was never really sure of what was and wasn’t real when the lights went out…and now her little brother, Martin, is experiencing the same unexplained and terrifying events that had once tested her sanity and threatened her safety. A frightening entity with a mysterious attachment to their mother, Sophie, has reemerged.",
      "release_date": "2016-07-22",
      "genre_ids": [
        27
      ],
      "id": 345911,
      "original_title": "Lights Out",
      "original_language": "en",
      "title": "Lights Out",
      "backdrop_path": "/mK9KdQj5Z6CAtxnFu2XPO8m78Il.jpg",
      "popularity": 4.483865,
      "vote_count": 133,
      "video": false,
      "vote_average": 6.11
    },
    {
      "poster_path": "/3mCcVbVLz23MhCngELFihX2uSwb.jpg",
      "adult": false,
      "overview": "XOXO follows six strangers whose lives collide in one frenetic, dream-chasing, hopelessly romantic night.",
      "release_date": "2016-08-26",
      "genre_ids": [
        18
      ],
      "id": 352492,
      "original_title": "XOXO",
      "original_language": "en",
      "title": "XOXO",
      "backdrop_path": "/dP3bxMPEDc9eNN2nH9P5YyhS27p.jpg",
      "popularity": 4.478293,
      "vote_count": 4,
      "video": false,
      "vote_average": 7
    },
    {
      "poster_path": "/zm0ODjtfJfJW0W269LqsQl5OhJ8.jpg",
      "adult": false,
      "overview": "As Batman hunts for the escaped Joker, the Clown Prince of Crime attacks the Gordon family to prove a diabolical point mirroring his own fall into madness. Based on the graphic novel by Alan Moore and Brian Bolland.",
      "release_date": "2016-07-24",
      "genre_ids": [
        28,
        16,
        80,
        18
      ],
      "id": 382322,
      "original_title": "Batman: The Killing Joke",
      "original_language": "en",
      "title": "Batman: The Killing Joke",
      "backdrop_path": "/7AxMc1Mgm3xD2lySdM6r0sQGS3s.jpg",
      "popularity": 4.136973,
      "vote_count": 141,
      "video": false,
      "vote_average": 5.91
    },
    {
      "poster_path": "/4J2Vc32juKTSdqm273HDKHsWO42.jpg",
      "adult": false,
      "overview": "A weekend getaway for four couples takes a sharp turn when one of the couples discovers the entire trip was orchestrated to host an intervention on their marriage.",
      "release_date": "2016-08-26",
      "genre_ids": [
        35,
        18
      ],
      "id": 351242,
      "original_title": "The Intervention",
      "original_language": "en",
      "title": "The Intervention",
      "backdrop_path": "/xvghzVFYDJd26Txy2s0rHORrXIi.jpg",
      "popularity": 4.113746,
      "vote_count": 7,
      "video": false,
      "vote_average": 3.79
    },
    {
      "poster_path": "/eZJYbODPWMRe6aQ1KtKHMb5ZOnx.jpg",
      "adult": false,
      "overview": "The adventures of teenager Max McGrath and alien companion Steel, who must harness and combine their tremendous new powers to evolve into the turbo-charged superhero Max Steel.",
      "release_date": "2016-08-26",
      "genre_ids": [
        878,
        28,
        12
      ],
      "id": 286567,
      "original_title": "Max Steel",
      "original_language": "en",
      "title": "Max Steel",
      "backdrop_path": "/9bM4Est3pyXPLr1vF2o5BiRtp0L.jpg",
      "popularity": 3.541536,
      "vote_count": 9,
      "video": false,
      "vote_average": 4.22
    },
    {
      "poster_path": "/v0krYaMdqD9uxFuFiWhEyKKIaw5.jpg",
      "adult": false,
      "overview": "Elite snipers Brandon Beckett (Chad Michael Collins) and Richard Miller (Billy Zane) tasked with protecting a gas pipeline from terrorists looking to make a statement. When battles with the enemy lead to snipers being killed by a ghost shooter who knows their exact location, tensions boil as a security breach is suspected. Is there someone working with the enemy on the inside? Is the mission a front for other activity? Is the Colonel pulling the strings?",
      "release_date": "2016-08-02",
      "genre_ids": [
        28,
        18,
        10752
      ],
      "id": 407375,
      "original_title": "Sniper: Ghost Shooter",
      "original_language": "en",
      "title": "Sniper: Ghost Shooter",
      "backdrop_path": "/yYS8wtp7PgRcugt6EUMhv95NnaK.jpg",
      "popularity": 3.504234,
      "vote_count": 17,
      "video": false,
      "vote_average": 4.76
    },
    {
      "poster_path": "/c4mvBk9cRAkyp9DpzlOBSmeuzG6.jpg",
      "adult": false,
      "overview": "Summer, New York City. A college girl falls hard for a guy she just met. After a night of partying goes wrong, she goes to wild extremes to get him back.",
      "release_date": "2016-08-26",
      "genre_ids": [
        18
      ],
      "id": 336011,
      "original_title": "White Girl",
      "original_language": "en",
      "title": "White Girl",
      "backdrop_path": "/dxUxtnxeMsI0jCUFAT6GbgyUdiz.jpg",
      "popularity": 3.485193,
      "vote_count": 8,
      "video": false,
      "vote_average": 1.88
    },
    {
      "poster_path": "/1SWIUZp4Gi2B6VxajpPWKhkbTMF.jpg",
      "adult": false,
      "overview": "The legendary Roberto Duran and his equally legendary trainer Ray Arcel change each other's lives.",
      "release_date": "2016-08-26",
      "genre_ids": [
        18
      ],
      "id": 184341,
      "original_title": "Hands of Stone",
      "original_language": "en",
      "title": "Hands of Stone",
      "backdrop_path": "/pqRJD5RE5DgRQ1Mq4kSZHmMjozn.jpg",
      "popularity": 3.474028,
      "vote_count": 16,
      "video": false,
      "vote_average": 3.75
    }
  ],
  "dates": {
    "maximum": "2016-09-01",
    "minimum": "2016-07-21"
  },
  "total_pages": 33,
  "total_results": 649
}

您看到它包装在results对象中。因此,您将需要以下内容:

public class RootObject
{
    public NowPlaying[] Results { get; set; }
}

然后反序列化为RootObjectquicktype.io是获取JSON对象结构的绝佳工具。或者,甚至可以将其烘焙到Visual Studio(仅Windows)中。复制JSON对象,然后转到编辑> 特殊粘贴> 将JSON作为类粘贴

Paste JSON as object in Visual Studio