首页 > 解决方案 > 防止空值显示在 API JSON 响应中

问题描述

我有一个像这样的简单 DTO 对象:

        var policyDetails = new PolicyDetailsDto
        {
            PolicyId = policy.Id,
            CustomerId = policy.CustomerId,
            AgentDetails = new AgentDetailsDto
            {
                AgencyName = offices?.MarketingName,
                AgencyPhoneNumbers = new List<string> { offices?.DapPhone, offices?.ContactPhone },
                AgentPhoneNumbers = new List<string> { employees?.BusinessPhone, employees?.HomePhone, employees?.MobilePhone }
            }
        };

当我将这个 dto 对象从我的 API 返回到客户端时,我得到了为 AgencyPhoneNumbers 和 AgentPhoneNumbers 显示的空值,如下所示:

{
"policyId": "4185a3b8-4499-ea11-86e9-2818784dcd69",
"customerId": "afb2a6e3-37a4-e911-bcd0-2818787e45b7",
"agentDetails": {
    "agencyName": "ABC Agency",
    "agencyPhoneNumbers": [
        "999-666-4000",
         null
    ],
    "agentPhoneNumbers": [
        "5555555555",
        null,
        null
    ]
}}

这是 AgentDetailsDto 类

[JsonObject(ItemNullValueHandling = NullValueHandling.Ignore)]
public class AgentDetailsDto
{
    public string AgencyName { get; set; }
    public List<string> AgencyPhoneNumbers { get; set; }
    public List<string> AgentPhoneNumbers { get; set; }
}

如何防止空值出现在我的 JSON 响应的列表中?

标签: c#asp.net-web-api

解决方案


您可以忽略 WebApiConfig 中的空值

config.Formatters.JsonFormatter.SerializerSettings = 
                 new JsonSerializerSettings {NullValueHandling = NullValueHandling.Ignore};

如果您使用的是 .NET Core,则可以使用它

public void ConfigureServices(IServiceCollection services)
{
     services.AddMvc()
             .AddJsonOptions(options => {
                options.JsonSerializerOptions.IgnoreNullValues = true;
     });
}

推荐阅读