【发布时间】: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