[英]Json Deserialize Error, Problem C# .Net Core
我在尝试反序列化从文件中读取的 JSON 时遇到以下问题。 我总是知道它不能被 object 类型反序列化。 这是什么原因造成的?
我的模型.cs
public class MyModel
{
public List<toppings> Lista { get; set; }
}
public class toppings
{
public string description { get; set; }
}
程序.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 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();
}
您可能需要稍微调整一下外壳。
此外,附带说明 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;}
}
您的toppings
是一个数组,其中每个项目都有 toppings 字符串数组。 所以,正确的 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; }
}
并反序列化为List<MyModel>
var result = JsonSerializer.Deserialize<List<MyModel>>(jsonString);
foreach (var item in result)
Console.WriteLine(string.Join(", ", item.Toppings));
它为您提供了一个包含 4 个项目的列表,其中每个项目都是一个包含单个字符串的列表
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.