I have a simple DTO object like this:
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 }
}
};
When I return this dto object from my API to the client, i am getting null values displayed for AgencyPhoneNumbers and AgentPhoneNumbers like this:
{
"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
]
}}
This is the AgentDetailsDto class
[JsonObject(ItemNullValueHandling = NullValueHandling.Ignore)]
public class AgentDetailsDto
{
public string AgencyName { get; set; }
public List<string> AgencyPhoneNumbers { get; set; }
public List<string> AgentPhoneNumbers { get; set; }
}
How can I prevent null values from showing up in the list in my JSON response?
You can ignore the null values in your WebApiConfig
config.Formatters.JsonFormatter.SerializerSettings =
new JsonSerializerSettings {NullValueHandling = NullValueHandling.Ignore};
if you are using .NET Core you can use this
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc()
.AddJsonOptions(options => {
options.JsonSerializerOptions.IgnoreNullValues = true;
});
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments