我有一個 JSON 檔案,其中包含按類別排序的產品。我正在嘗試反序列化 JSON,所以我得到一個 List<List> 以便我可以輕松訪問例如“收藏夾”中的產品。
我看到了使用 JSON 的問題,因為我還需要類別名稱,我現在將它們存盤在產品本身中。我想要實作的是輕松獲取存盤在“收藏夾”或其他產品中的所有產品。
我的主要問題是我不確定哪種資料型別更適合存盤此類資訊。我的 JSON 是:
{
"Favoritos": [
{
"Categoria" : "CortePelo",
"Nombre" : "Corte Hombre",
"Precio" : "10,00",
"Color" : "57; 62; 65"
},
{
"Categoria" : "CortePelo",
"Nombre" : "Corte Mujer",
"Precio" : "100,00",
"Color" : "57; 62; 65"
}
],
"CortePelo": [
{
"Categoria" : "CortePelo",
"Nombre" : "Corte Hombre",
"Precio" : "10,00",
"Color" : "57; 62; 65"
},
{
"Categoria" : "CortePelo",
"Nombre" : "Corte Mujer",
"Precio" : "100,00",
"Color" : "57; 62; 65"
}
]
}
我的課程是:
public class Productos
{
public List<List<Producto>> Categorias { get; set; }
}
public class Producto
{
public string Categoria { get; set; }
public string Nombre { get; set; }
public double Precio { get; set; }
public string Color { get; set; }
[JsonConstructor]
public Producto(string categoria, string nom, double prc, string color)
{
Categoria = categoria;
Nombre = nom;
Precio = prc;
Color = color;
}
}
而且我在反序列化中得到了空值:
string json = r.ReadToEnd();
Productos productos = JsonConvert.DeserializeObject<Productos>(json);
uj5u.com熱心網友回復:
您的 JSON 與 中定義的架構不匹配Productos。不要使用Productos該類,Dictionary<string,Producto[]>而是使用與 JSON 更匹配的類。
像這樣:
string json = r.ReadToEnd();
Dictionary<string,Producto[]> productosPorCategoria = JsonConvert.DeserializeObject<Dictionary<string,Producto[]>>(json);
注意:如果變數名不正確,我很抱歉,我使用了谷歌翻譯。
如果您仍想強烈鍵入屬性而不是使用字典,則需要Productos像這樣更新:
public class Productos
{
public List<Producto> Favoritos { get; set; }
public List<Producto> CortePelo { get; set; }
}
uj5u.com熱心網友回復:
由于反序列化失敗,您將獲得空值。但它沒有拋出例外。
正確的型別是 Dictionary<string, Producto[]>
如果你想檢查你的 deearilation 是否正確,首先創建你的物件結構的序列化 json 物件。
uj5u.com熱心網友回復:
嗨,您如何制作一個 Producto 串列并將其序列化到 json 中,檢索后您只需將 json 反序列化為一個串列,然后按類別對 Producto 串列進行分組,現在您可以使用按類別分組的產品串列串列LINQ。
{
[
{"Categoria" : "CortePelo",
"Nombre" : "Corte Hombre",
"Precio" : "10,00",
"Color" : "57; 62; 65"
},{
"Categoria" : "CortePelo",
"Nombre" : "Corte Mujer",
"Precio" : "100,00",
"Color" : "57; 62; 65"
},{
"Categoria" : "CortePelo",
"Nombre" : "Corte Hombre",
"Precio" : "10,00",
"Color" : "57; 62; 65"
},{
"Categoria" : "CortePelo",
"Nombre" : "Corte Mujer",
"Precio" : "100,00",
"Color" : "57; 62; 65"
}
]
}
在這里,您將 json 反序列化為 Producto 串列
string json = r.ReadToEnd();
List<Producto>productos = JsonConvert.DeserializeObject<List<Producto>>(json);
//Here you now group the list of Producto by Categoria
var groupedProductos=productos.GroupBy(x=>x.Categoria);
//To find Products with Categoria 'CortePelo'
var cortePeloGroup=groupedProductos.FirstOrDefault(x=>x.Key=="CortePelo");
//Now you convert the Grouped Producto of Categoria 'CortePelo' to List
List<Producto> cortePeloProductoList = cortePeloGroup.Select(g => g).ToList();
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/448775.html
