c# - 防止空值显示在 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 响应的列表中?
解决方案
您可以忽略 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;
});
}
推荐阅读
- visual-studio-code - 如何在 vscode 的 Multi-root Workspaces 中获取活动工作区
- javascript - 当我保存方法的返回时,它保存未定义
- laravel-8 - Doctrine\DBAL\Driver\PDO\Exception SQLSTATE[28000] [1045] Access denied for user 我得到一个错误
- html - 如何为 tbody 中的所有表数据设置一个表头?
- javascript - 如何下载远程图像然后将图像作为图像文件上传以进行表单提交?
- r - 如何在 Rstudio 上的模糊逻辑变量中同时使用多个成员资格(三角形和梯形)?
- kerberos - traefik v2 重定向 TCP 请求
- macros - Doyxgen一次性宏扩展/扩展命令
- jenkins - 尝试使用 Homebrew 安装 jenkins 时出错
- azure-blob-storage - Azure Blob 存储不在本地存储