簡體   English   中英

如何將 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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM