102

I've created an ASP.Net WEB API Project that will be used by a mobile application. I need the response json to omit null properties instead of return them as property: null.

How can I do this?

7 Answers 7

143

In the WebApiConfig:

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

Or, if you want more control, you can replace entire formatter:

var jsonformatter = new JsonMediaTypeFormatter
{
    SerializerSettings =
    {
        NullValueHandling = NullValueHandling.Ignore
    }
};

config.Formatters.RemoveAt(0);
config.Formatters.Insert(0, jsonformatter);
Sign up to request clarification or add additional context in comments.

8 Comments

Shame config.Formatters.XmlFormatter doesn't have the same Property... :/
Since Json.NET 5 (not sure for previous versions), you can also do this: config.Formatters.JsonFormatter.SerializerSettings.NullValueHandling = NullValueHandling.Ignore - this will update the null value handling without resetting any other json serialization settings (like using lower case on the first letter of properties)
Is it possible to get it to do it for just a single property?
the NullValueHandling = NullValueHandling.Ignore did not work for my results
If the change should happen on a per-property basis, and one is using a sufficiently new version of Json.Net, one can use this attribute on the property: [JsonProperty(NullValueHandling = NullValueHandling.Ignore)].
|
33

I ended up with this piece of code in the startup.cs file using ASP.NET5 1.0.0-beta7

services.AddMvc().AddJsonOptions(options =>
{
    options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
});

Comments

22

For ASP.NET Core 3.0, the ConfigureServices() method in Startup.cs code should contain:

services.AddControllers()
    .AddJsonOptions(options =>
    {
        options.JsonSerializerOptions.IgnoreNullValues = true;
    });

1 Comment

This is the best option, because on the API (without MVC) you don't have MVC implemented.
8

You can also use [DataContract] and [DataMember(EmitDefaultValue=false)] attributes

1 Comment

This is the only answer that covers both the xml and json response.
5

If you are using vnext, in vnext web api projects, add this code to startup.cs file.

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc().Configure<MvcOptions>(options =>
        {
            int position = options.OutputFormatters.FindIndex(f =>  f.Instance is JsonOutputFormatter);

            var settings = new JsonSerializerSettings()
            {
                NullValueHandling = NullValueHandling.Ignore
            };

            var formatter = new JsonOutputFormatter();
            formatter.SerializerSettings = settings;

            options.OutputFormatters.Insert(position, formatter);
        });

    }

Comments

3

Since I cannot comment due to my low reputation. Adding to Dave Wegner's answer since it is obsolete the current solution is:

services.AddControllers().AddJsonOptions(options =>
            options.JsonSerializerOptions.DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull
        );

Comments

0
builder.Services.AddControllersWithViews().AddJsonOptions(options =>
{  
    options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
});

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.