【问题标题】:Can we ignore a c# list from class property? [duplicate]我们可以忽略类属性中的 c# 列表吗? [复制]
【发布时间】:2020-08-13 09:32:09
【问题描述】:

如果 List 为 null,c# 中有什么机制可以忽略它吗?

public class VehicleResponse 
  {
        public Pagination pagination { get; set; }
        public Vehicles data { get; set; }        
        public Include include { get; set; }
    }

此处包含类属性可能为空。如果它为空,那么我想忽略该属性。

 public class Include
    {
        
        public List<Devices> devices { get; set; }
        public List<Institutions> institutions { get; set; }
        public List<Cars> cars{ get; set; }
    }

这是包含的类。如果任何列表(如设备、机构或汽车)为空,则应将其忽略。

我不想在我的 json 响应中显示空值。如果它们为空,则忽略它们。

【问题讨论】:

  • “我不想在我的 json 响应中显示空值”——这是关键部分。 (没有一般忽略属性的概念。)现在,您使用的是哪个 JSON 序列化程序?在 Json.NET (Newtonsoft.Json) 中肯定有一个设置。我不确定 System.Text.Json。
  • “我不想在我的 json 响应中显示空值。” - 你可能想让这一点更明显一点。在最后一行之前,我真的很困惑您所说的“忽略”是什么意思。您可能还想使用您正在使用的相应 JSON 序列化程序来标记您的问题。由于您已标记 ASP.NET Core,因此这很可能是 JSON.NET 或 System.Text.Json。
  • { "pagination": { "offset": 1, "limit": 4, "total": 1 }, "data": { "vehicles": [ { "vehicleId": 6, "deviceId": 1, } ] }, "include": { "devices": [ { "deviceId": 1, "serialNumber": "1234567890" } ], "institutions": null, "models": null }, "status": true, "message": "车辆检索成功。", "responseCode": 200 }
  • @John 以上是我基于我的类属性的 json 响应。这里“机构”和“模型”为空,所以我不想在 json 响应中显示。
  • 为什么我删除了 ASP.NET 标签后又重新添加了它?该标签的描述清楚地表明它不应该用于 ASP.NET Core 问题。另外,您还没有告诉我们您使用的是哪个 JSON 序列化程序。

标签: c# class asp.net-core properties


【解决方案1】:

您必须创建一个空的构造函数来初始化这些列表,JSON 结果将是空列表。

public class Include
    {
        public Include(){
           devices = new List<Devices>();
           institutions = new List<Institutions>();
           cars= new List<Cars>();
        }
        public List<Devices> devices { get; set; }
        public List<Institutions> institutions { get; set; }
        public List<Cars> cars{ get; set; }
    }

编辑

我刚刚找到了这个.NET Core: Remove null fields from API JSON response 我希望它可以提供帮助。否则我建议您编写自己的 OutputFormatter

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2016-03-17
  • 1970-01-01
  • 2019-09-19
  • 2011-06-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多