Json 反序列化错误,问题 C# .Net Core

Json Deserialize Error, Problem C# .Net Core

我在尝试反序列化从文件中读取的 JSON 时遇到以下问题。我总是知道它不能按对象类型反序列化。这是什么原因造成的?

MyModel.cs

public class MyModel
{
    public List<toppings> Lista { get; set; }
}
public class toppings
{
    public string description { get; set; }
}

Program.cs

static void Main(string[] args)
{
    try
    {
        string json = File.ReadAllText(@"C:\Users\Ricciardo\Documents\Net Core Practice\Pizza\PizzaRead\pizzas.json").ToString();

        MyModel objetos = JsonSerializer.Deserialize<MyModel>(json);

        foreach (var ingrediente in objetos.Lista)
        {
            Console.WriteLine(ingrediente.description.ToString());
        }
    }

    catch (Exception ex)
    {
        Console.Write(ex.Message.ToString());
        throw ex;
    }
    Console.ReadKey();
}

JSON 文件

[
  {
    "toppings": [
      "pepperoni"
    ]
  },
  {
    "toppings": [
      "feta cheese"
    ]
  },
  {
    "toppings": [
      "pepperoni"
    ]
  },
  {
    "toppings": [
      "bacon"
    ]
  }
]

您的 class 结构似乎与您的 JSON 结构不匹配。

您的 JSON 结构如下:

  • 数组
    • 对象
      • 数组(浇头)

定义您的 MyModel(或 Pizza)class:

public class Pizza
{
    public List<string> Toppings {get; set;}
}

然后更新你的Program.cs主要方法:

    static void Main(string[] args)
    {
        try
        {
            string json = File.ReadAllText(@"C:\Users\Ricciardo\Documents\Net Core Practice\Pizza\PizzaRead\pizzas.json").ToString();

            var objetos = JsonSerializer.Deserialize<List<Pizza>>(json);

            foreach (var pizza in objetos)
            {
                //Console.WriteLine(ingrediente.description.ToString());
                // TODO: Manipulate pizza objeto
            }
        }

        catch (Exception ex)
        {
            Console.Write(ex.Message.ToString());
            throw ex;
        }
        Console.ReadKey();
    }

您可能需要稍微调整外壳。

此外,请注意 JSON 的结构方式会带来一些问题。

类似这样的结构可能会帮助你更多:

[
  {
    "Toppings": [
        {
          "name":"pepperoni"
          "description":"blah"
        },
    ]
  },
]

然后你实际上可以像这样定义一个 Topping class:

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

    public string Description {get; set;}
}

然后换披萨 class (MyModel):

public class Pizza 
{
    public List<Topping> Toppings {get; set;}
}

您的 JSON 是一个数组,其中每个项目都有 toppings 个字符串数组。所以,正确的模型应该是这样的(用 JsonPropertyName 属性装饰)

using System.Text.Json;
using System.Text.Json.Serialization;

//rest of code

public class MyModel
{
    [JsonPropertyName("toppings")]
    public List<string> Toppings { get; set; }
}

并反序列化为List<MyModel>

var result = JsonSerializer.Deserialize<List<MyModel>>(jsonString);
foreach (var item in result) 
    Console.WriteLine(string.Join(", ", item.Toppings));

它给你一个包含 4 个项目的列表,其中每个项目都是一个包含单个字符串的列表