简体   繁体   English

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

[英]Json Deserialize Error, Problem C# .Net Core

I have the following problem trying to deserialize JSON that I read from a file.我在尝试反序列化从文件中读取的 JSON 时遇到以下问题。 I always get that it can't be deserialized by object type.我总是知道它不能被 object 类型反序列化。 What is causing this?这是什么原因造成的?

MyModel.cs我的模型.cs

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

Program.cs程序.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 File JSON 文件

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

It appears that your class structure doesn't match your JSON structure.您的 class 结构似乎与您的 JSON 结构不匹配。

Your JSON is structured as such:您的 JSON 的结构如下:

  • Array大批
    • Object Object
      • Array (toppings)阵列(浇头)

Define your MyModel (or Pizza) class:定义您的 MyModel(或 Pizza)class:

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

Then update your Program.cs Main method:然后更新您的 Program.cs Main 方法:

    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();
    }

You may have to tweak with the casing a little.您可能需要稍微调整一下外壳。

Also, a side note the way the JSON is structured poses some problems.此外,附带说明 JSON 的结构方式会带来一些问题。

A structure similar to this may help you out more:与此类似的结构可能会帮助您更多:

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

Then you could actually define a Topping class like so:然后你实际上可以像这样定义一个 Topping class :

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

    public string Description {get; set;}
}

And change up the Pizza class (MyModel):并更换披萨 class(MyModel):

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

Your JSON is an array, where every item has toppings array of strings.您的toppings是一个数组,其中每个项目都有 toppings 字符串数组。 So, the proper model should be something like that (decorated with JsonPropertyName attribute)所以,正确的 model 应该是这样的(用JsonPropertyName属性装饰)

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

//rest of code

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

And deserialization to List<MyModel>并反序列化为List<MyModel>

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

It gives you a list with 4 items, where every item is a list with single string inside它为您提供了一个包含 4 个项目的列表,其中每个项目都是一个包含单个字符串的列表

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM