【发布时间】:2021-01-25 17:37:08
【问题描述】:
我正在尝试将 JSON 文件反序列化为 c# 类。但是,我的反序列化方法总是返回 null。 我的 JSON 文件如下所示-
{
"Products": [
{
"ProductID": 994,
"Name": "LL Bottom Bracket",
"ProductNumber": "BB-7421",
"ProductCategoryID": 9,
"ProductCategory": "Bottom Brackets",
"ProductModelID": 95,
"Description": "Chromoly steel."
},
{
"ProductID": 995,
"Name": "ML Bottom Bracket",
"ProductNumber": "BB-8107",
"ProductCategoryID": 9,
"ProductCategory": "Bottom Brackets",
"ProductModelID": 96,
"Description": "Aluminum alloy cups; large diameter spindle."
}
]
}
我正在尝试将其序列化为以下类-
public class Product
{
[JsonProperty("ProductID")]
public long ProductId { get; set; }
[JsonProperty("Name")]
public string Name { get; set; }
[JsonProperty("ProductNumber")]
public string ProductNumber { get; set; }
[JsonProperty("ProductCategoryID")]
public long ProductCategoryId { get; set; }
[JsonProperty("ProductCategory")]
public string ProductCategory { get; set; }
[JsonProperty("ProductModelID")]
public long ProductModelId { get; set; }
[JsonProperty("Description")]
public string Description { get; set; }
[JsonProperty("Color", NullValueHandling = NullValueHandling.Ignore)]
public string Color { get; set; }
}
public partial class Products
{
[JsonProperty("Products")]
public IEnumerable<Product> ProductsProducts { get; set; }
}
最后,我正在使用此代码对其进行反序列化,但由于某种原因它返回 null。有人可以帮忙吗?
public Products Get()
{
var jsonString = IO.File.ReadAllText("ProductsData.json");
var products = JsonSerializer.Deserialize<Products>(jsonString);
return products;
}
【问题讨论】:
-
将
IEnumerable<Product>用于"Products"属性可能会出现问题 - 如果不起作用,请尝试将其设为ICollection<Product>或List<Product>。对于更优雅的解决方案,我相信有一种方法可以设置默认集合实现,但我不知道它是什么。 -
我已经尝试过使用 List 和 ICollection 但不幸的是它仍然无法正常工作。
标签: c# json deserialization json-deserialization