【问题标题】:ASP.Net Controller improperly Deserializing nested list of objectsASP.Net 控制器不正确地反序列化嵌套的对象列表
【发布时间】:2020-09-04 21:50:58
【问题描述】:

我有以下 C# 类型定义:

public class GraphicSubmission
    {
        public string Title { get; set; }
        public string Description { get; set; }
        public string Byline { get; set; }
        public string BylineTitleId { get; set; }
        public string BylineTitleDescription { get; set; }
        public string Category { get; set; }

        public List<GraphicBinary> GraphicBinaries;

        public GraphicSubmission()
        {
            GraphicBinaries = new List<GraphicBinary>();
        }
    }

其中包括这些对象的嵌套列表:

   public class GraphicBinary
    {
        public SubmittedImageType ImageType { get; set; }
        public string OriginalFilename { get; set; }
        public string ItemId { get; set; }
        public string RecordId { get; set; }
        public int RecordSequenceNumber { get; set; }
    }

我有以下 Controller 方法,它的参数之一是 GraphicSubmission 对象:

        [HttpPost]
        public JsonResult Graphic(PhotoAction actionType, bool hid, GraphicSubmission graphicModel)

当我从 AngularJS 站点调用控制器方法时,HTTP POST 正文中包含以下 JSON:

{
    "Title": "AP Poll Stay at Home Protest Approval",
    "Description": "A new UChicago Divinity School/AP-NORC poll finds that two-thirds of Democrats and about half of Republicans disapprove of recent protests of stay at home orders.;",
    "Byline": "F. Strauss",
    "BylineTitleDescription": "STAFF",
    "BylineTitleId": "STF",
    "Category": "a",
    "GraphicBinaries": [
        {
            "ImageType": "PrintGraphicAI",
            "ItemId": "dd142b48fe7c4cc6bf9b42c9c9402e7d",
            "RecordId": "dd142b48fe7c4cc6bf9b42c9c9402e7d",
            "RecordSequenceNumber": 0,
            "OriginalFilename": "ChicagoShootings.ai"
        },
        {
            "ImageType": "PrintGraphicJPEG",
            "ItemId": "ccce25ddc1cb45d898b09eb0d91fcecc",
            "RecordId": "ccce25ddc1cb45d898b09eb0d91fcecc",
            "RecordSequenceNumber": 0,
            "OriginalFilename": "ChicagoShootings.jpg"
        }
    ]
}

该方法已正确调用,但 GraphicSubmission 对象的 GraphicBinaries 字段始终为空。

鉴于 JSON,我希望它包含 2 个条目。

我的问题是我需要做什么才能让 ASP.Net 正确反序列化嵌套的对象列表?

我在这里看过一些相关的文章,例如:

Deserialize JSON array(or list) in C#

Passing JSON Object and List of Objects to ASP.Net Controller [duplicate]

Post JSON array to mvc controller

但他们似乎都没有解决这个问题的关键。

【问题讨论】:

  • GraphicBinaries 设为属性而非字段。不要在 ctor 中初始化列表。
  • 您缺少GraphicBinaries 末尾的{ get; set; } 属性访问器。这意味着 C# 将其解释为字段而不是属性,因此不会被序列化。

标签: c# asp.net json deserialization json-deserialization


【解决方案1】:

正如 cmets 指出的,GraphicSubmission 类中的 GraphicBinaries 字段需要通过添加 { get;放; }。

这里有一篇文章指出了区别:

What is the difference between a field and a property?

【讨论】:

    猜你喜欢
    • 2019-03-08
    • 1970-01-01
    • 2016-06-29
    • 1970-01-01
    • 2018-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-26
    相关资源
    最近更新 更多