【问题标题】:WPF - Json.NET: How do I deserialize multiple objects from Json and put it in an List?WPF - Json.NET:如何从 Json 反序列化多个对象并将其放入列表中?
【发布时间】:2021-11-11 18:45:43
【问题描述】:

文件:data.json:

[
  {
    "Items": [
      {
        "Name": "Item 0"
      },
      {
        "Name": "Item 1"
      },
      {
        "Name": "Item 2"
      }
    ] 
  }
]

类:

public partial class ItemHandler : Page
{
    string itemsJson;
    public ItemHandler()
    {
        InitializeComponent();

        itemsJson = JsonHandler.ReadItems();

        foreach (var item in collection)
        {
            // ???
        }
    }
}

public class Item
{
    public string Name { get; set; }
}

我需要按名称从字符串列表中获取每个项目,但我不知道如何逐个反序列化,我对 Json.NET 反序列化教程感到困惑。

【问题讨论】:

  • 如果使用 Visual Studio,您可以使用特殊粘贴。将json复制到剪贴板,然后使用Edit/Paste Special/Paste JSON as Classes

标签: c# json wpf .net-core


【解决方案1】:

试试这个

void Main()
{
    var json ="[{\"Items\":[{\"Name\":\"Item 0\"},{\"Name\":\"Item 1\"},{\"Name\":\"Item 2\"}]}]";

    var jD=JsonSerializer.Deserialize<Root[]>(json);

    foreach (var items in jD)
    {
        foreach (var item in items.Items)
        {
            Console.WriteLine(item.Name);
        }
    }

}

public class Item
{
    public string Name { get; set; }
}

public class Root
{
    public List<Item> Items { get; set; }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-22
    相关资源
    最近更新 更多