我试图将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;
}
型
4条答案
按热度按时间nnsrf1az1#
因为
您正在使用
Netwonsoft.Json
包中的JsonProperty
属性,但内置的.NET Core/5解析器来自System.Text.Json
命名空间。Newtonsoft.Json没有
JsonSerializer.Deserialize
重载,它只接受一个字符串,.NET也不包含JsonPropertyAttribute
。这两者不兼容。.NET解析器忽略您的
[JsonProperty("Products")]
属性,在JSON中找不到名为ProductsProducts
的属性,因此该属性为null。修复
要使用Newtonsoft.Json包中的解析器,请替换
字符串
与
型
下面是代码的一个工作小提琴:https://dotnetfiddle.net/27Tz4t
1bqhqjot2#
使用NewtonsoftJson
字符串
使用System.Text.Json
型
nnvyjq4y3#
如果你有json响应,只使用这个网站转换Json to c# class
字符串
或者使用visual studio选项Edit-->Paste Special-->Paste JSON as Classes
型
frebpwbc4#
使用System.Text.Json;
根据微软官方文档(https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/customize-properties?pivots=dotnet-8-0),“web默认命名策略是camel case”。
字符串
在.NET 8中,可以指定JSON在序列化/解序列化时可以使用的命名策略
型