[英]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.