如何将 JSON 列表反序列化为 C# 对象列表

How to deserialize JSON list to C# List of objects

从 AWS lambda 我得到这个 JSON 字符串:

[{"Id":19162,"LotId":21243,"LotNumber":"H6469","LotType":20,"ConfirmationStatus":0,"Date":"2016-02-17T10:51:06.757"},{"Id":19163,"LotId":21244,"LotNumber":"H6469a","LotType":20,"ConfirmationStatus":0,"Date":"2016-02-17T10:51:19.933"}]

我已经声明了一个 class,我想反序列化从这个 API 接收到的数据。

public class GetWesLotToGenerateReturn
    {
        public long Id { get; set; }
        public long LotId { get; set; }
        public string LotNumber { get; set; }
        public int LotType { get; set; }
        public int ConfirmationStatus { get; set; }
        public DateTime Date { get; set; }
    }

我正在尝试这样做:

List<GetWesLotToGenerateReturn> sample = JsonSerializer.Deserialize<List<GetWesLotToGenerateReturn>>(lots);

我收到此错误:

The JSON value could not be converted to System.Collections.Generic.List`1[Service.App.Models.AdaptersModels.GetWesLotToGenerateReturn]. Path: $ | LineNumber: 0 | BytePositionInLine: 268.

如何正确地将 JSON 从列表反序列化为 C# 中的对象列表?

提前致谢!

你的json

json= "\"[{\\"Id\\":19162,\\"LotId\\":21243,\\"LotNumber\\":\\"H6469\\",\\"LotType\\":20,\\"ConfirmationStatus\\":0,\\"Date\\":\\"2016-02-17T10:51:06.757\\"},{\\"Id\\":19163,\\"LotId\\":21244,\\"LotNumber\\":\\"H6469a\\",\\"LotType\\":20,\\"ConfirmationStatus\\":0,\\"Date\\":\\"2016-02-17T10:51:19.933\\"}]\"";

你的json被序列化了两次(可能是使用JSON.stringify),需要先修复

json=JsonConvert.DeserializeObject<string>(json);

在此之后我使用 Serializer(MS 和 Newtonsoft)对其进行了反序列化,一切正常

var jd = JsonConvert.DeserializeObject<List<GetWesLotToGenerateReturn>>(json);

var jdm = System.Text.Json.JsonSerializer.Deserialize<List<GetWesLotToGenerateReturn>>(json);