问题描述
在我的 .Net Core 3.1 Web 应用程序中,我有一个由后端和前端共享的类,如下所示
public class Order
{
[Key]
[required]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public DateTime OrderTime { get; set; }
public int UserId { get; set; }
public int Vat { get; set; }
[NotMapped]
public Dictionary<string,int> Products { get; set; }
public int discount { get; set; }
public float ShippingPrice { get; set; }
public bool Shipped { get; set; }
public bool Cancelled { get; set; }
public string CancelReason { get; set; }
public Order()
{
}
}
在前端,我使用 HttpClient 从 REST API 获取订单列表。
httpClient 接收到的 Json 看起来像:
[
{
"id": 1,"orderTime": "2021-01-28T14:55:03.077","userId": 0,"vat": 0,"products": null,"discount": 0,"shippingPrice": 0,"shipped": true,"cancelled": true,"cancelReason": "string"
},{
"id": 2,"userId": 2,"discount": 10,"shipped": false,"cancelled": false,"cancelReason": null
}
]
对于反序列化,我使用的是 JsonSerializer:
var returnorders = await JsonSerializer.DeserializeAsync<List<Order>>(await response.Content.ReadAsstreamAsync());
从中我确实在 List 上获得了正确数量的对象,但它们的值都为 0 或 null 等。 我做错了什么?
在我使用 ReadAsAsync() 之前,它运行良好,但在 .Net core 3 中已弃用
await response.Content.ReadAsAsync<List<Object>>();
解决方法
默认情况下,JsonSerializer 在 json 中查找与您的类中定义的名称相同的属性。在您的情况下,您使用的是 CamelCase 命名约定,因此您需要像这样指定它:
var options = new JsonSerializerOptions()
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,};
var returnOrders = await JsonSerializer.DeserializeAsync<List<Order>>(await response.Content.ReadAsStreamAsync(),options);
,
这可能是由于不同反序列化器使用的 JSON 反序列化约定造成的。例如,有时 JSON 键的大小写很重要。
尝试使用 NewtonsoftJSON 反序列化器而不是您使用的默认反序列化器。它将在不检查大小写的情况下解析 JSON。
string json = @"{
'Email': 'james@example.com','Active': true,'CreatedDate': '2013-01-20T00:00:00Z','Roles': [ 'User','Admin' ]
}";
Account account = JsonConvert.DeserializeObject<Account>(json);
Console.WriteLine(account.Email);