简体   繁体   English

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

[英]How to deserialize JSON list to C# List of objects

from the AWS lambda I get this JSON string:从 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"}]

I have declared a class to which I want to deserialize the data received from this API.我已经声明了一个 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; }
    }

I'm trying to do this:我正在尝试这样做:

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

And I receive this error:我收到这个错误:

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

How can I properly deserialize JSON from a list to a list of objects in C#?如何正确地将 JSON 从列表反序列化为 C# 中的对象列表?

Thanks in advance!提前致谢!

your json你的 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\\\"}]\"";

your json was serialized twice (probably by using JSON.stringify) and needs to be fixed at first您的 json 被序列化了两次(可能是通过使用 JSON.stringify),首先需要修复

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

after this I deserialized it using both Serializer (MS and Newtonsoft) and everything is ok在此之后,我使用 Serializer(MS 和 Newtonsoft)对其进行反序列化,一切正常

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM