【问题标题】:Json to ListView - Can't convert type to IEnumerable- XamarinJson 到 ListView - 无法将类型转换为 IEnumerable - Xamarin
【发布时间】:2020-04-24 12:56:47
【问题描述】:

我很难弄清楚如何将我的 json 数据绑定到列表视图。我有一个错误 topList.ItemsSource = recipes;这是“无法将类型Recipes 隐式转换为IEnumerable。您是否缺少演员表?”

XAML

<ListView x:Name="topList">
        <ListView.ItemTemplate>
            <DataTemplate>
                <Label Text="{Binding Title}"/>
            </DataTemplate>
        </ListView.ItemTemplate>
</ListView>

C#

        Recipes recipes;
        public HomePage()
        {
            InitializeComponent();
            ReadJson();

        }

        void ReadJson()
        {
            var assembly = typeof(MainPage).GetTypeInfo().Assembly;
            Stream stream = assembly.GetManifestResourceStream("Recipes.json");

            using (var reader = new StreamReader(stream))
            {
                var json = reader.ReadToEnd();
                recipes = JsonConvert.DeserializeObject<Recipes>(json);

                topList.ItemsSource = recipes;

            }
        }

public class Recipes
    {
        public List<Recipe> Recipe { get; set; }
    }

    public class Recipe
    {
        public string Title { get; set; }
        public string Img { get; set; }
    }

Json 文件

{
  "Recipe": [
    {
      "title": "Satay Chicken Skewers",
      "img": "satayChicken.jpg"
    },
    {
      "title": "Sweet Potato Spinach Feta Pie",
      "img": "SweetPotatoSpinachFetaPie.jpg"
    }
  ]
}

【问题讨论】:

    标签: c# json xaml xamarin


    【解决方案1】:

    recipes 是单个对象。 recipes.Recipe 是一个列表(或IEnumerable

    topList.ItemsSource = recipes.Recipe;
    

    【讨论】:

    • 当我尝试这个时,我的程序进入中断模式 - System.InvalidCastException: 'Specified cast is not valid.'
    • 根据您发布的代码应该是。它认为recipes.Recipe 是什么类型?
    • System.Collections.Generic.List[配方]
    • 没错。必须有另一行导致异常。检查堆栈跟踪
    • 当我删除那一行时,程序至少会启动,所以我看不出它怎么可能是另一行。我也尝试将它包装在 try and catch 中,但它直接进入了中断模式,并且只给了我在第一条评论中提到的错误,并且没有机会运行 catch 语句。我不知道是什么导致了错误...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多