【问题标题】:Deserialize JSON object as .NET HashSet and Lists Failed将 JSON 对象反序列化为 .NET HashSet 和列表失败
【发布时间】:2021-07-14 22:56:14
【问题描述】:

我有这种想要保存的 Json:

 "data": {
      "importMannerTypeList": {
        "importMannerTypeID": 5,
        "importMannerTypeDesc": "a"
      },
      "authoritySourceList": [
        {
          "authoritySourceID": 1,
          "authoritySourceDesc": "b"
        }
      ],
      "permitStatusList": {
        "permitStatusID": 4,
        "permitStatusDesc": "c"
      }}

它们都设置为数组,但是因为authoritySourceList 是多选而不是 1 个对象,所以看起来像这样。这里是反序列化json的类,importMannerTypeListpermitStatusList无法从JSON获取数据,为什么?

public class ImportPlantSettingsResponse
    {
        public ImportPlantSettingsResponse()
        {
            ImportMannerTypeList = new List<ImportMannerType>();
            AuthoritySourceList = new HashSet<AuthoritySource>();
            PermitStatusList = new List<PermitStatusResponse>();
        }

        public virtual List<ImportMannerType> ImportMannerTypeList { get; set; }
        public virtual ICollection<AuthoritySource> AuthoritySourceList { get; set; }
        public virtual List<PermitStatusResponse> PermitStatusList { get; set; }

【问题讨论】:

  • 我建议你阅读Json Arrays,因为importMannerTypeList的值不是Json中的数组,permitStatusList也是。
  • 那些不是 JSON 数组,它们是 JSON 对象。您的问题中显示的 JSON 没有任何数组,这些数组是以 [ 开头、以 ] 结尾并包含逗号分隔的 JSON 值的容器。有关详细信息,请参阅json.org。由于 Newtonsoft 根据 the documentation 将集合(例如 HashSet&lt;T&gt;)序列化为 JSON 数组,因此如果没有自定义转换器,您将无法将非数组对象反序列化为哈希集。

标签: c# arrays json asp.net-core .net-core


【解决方案1】:

正如Selim Yildiz 所说,ImportMannerTypeList 和 PermitStatusList 不是列表。这是一个演示:

型号:

public class ImportPlantSettingsResponse
    {
        public ImportPlantSettingsResponse()
        {
            AuthoritySourceList = new HashSet<AuthoritySource>();
        }

        public virtual ImportMannerType ImportMannerTypeList { get; set; }
        public virtual ICollection<AuthoritySource> AuthoritySourceList { get; set; }
        public virtual PermitStatusResponse PermitStatusList { get; set; }
    }

行动:

public IActionResult TestImportPlantSettingsResponse([FromBody] ImportPlantSettingsResponse importPlantSettingsResponse) {
            return Ok();
        }

结果:

【讨论】:

    猜你喜欢
    • 2017-01-28
    • 2012-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多