0

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?

1
  • 1
    Do not add null values to the list or remove them with LINQ Commented May 27, 2020 at 4:52

1 Answer 1

3

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;
     });
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.