我有一个简单的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 }
}
};
[当我从我的API返回此dto对象到客户端时,我得到的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;
});
}