Suppress Properties with Null Value on ASP.NET Web API

Suppress properties with null value on ASP.NET Web API

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);

.NET Core: Remove null fields from API JSON response

.NET Core 1.0

In Startup.cs, you can attach JsonOptions to the service collection and set various configurations, including removing null values, there:

public void ConfigureServices(IServiceCollection services)
{
services.AddMvc()
.AddJsonOptions(options => {
options.SerializerSettings
.NullValueHandling = NullValueHandling.Ignore;
});
}
.NET Core 3.1

Instead of this line:

options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;

Use:

options.JsonSerializerOptions.IgnoreNullValues = true;
.NET 5.0

Instead of both variants above, use:

 options.JsonSerializerOptions.DefaultIgnoreCondition 
= JsonIgnoreCondition.WhenWritingNull;

The variant from .NET Core 3.1 still works, but it is marked as NonBrowsable (so you never get the IntelliSense hint about this parameter), so it is very likely that it is going to be obsoleted at some point.

Ignore Null properties/values in Web Api with OData response Owin Self-Host

After dealing two nights with a possible answer I think I have found a possible solution, however, the resources have the answer you mentioned, personally the part of Dependency Injection to register the serializer was the most difficult, but I must give credit to this question, it was helpful: How to register an OData Serializer Provider with AspNet.OData v6

Finally I share what a solution could represent:

Following the Microsoft documentation for create the project:

https://learn.microsoft.com/en-us/aspnet/web-api/overview/odata-support-in-aspnet-web-api/odata-v4/create-an-odata-v4-endpoint

1. An ASP .NET 4.7.2 project is created with WebApi template
2. Use the Microsoft.AspNet.OData package in its version 7.5.0:

Sample Image

3. The controller is this:

public class ItemsController : ODataController
{
public static List<Item> items = new List<Item>()
{
new Item { Id = 1, Name = "name1", OptionalField = "Value Present" },
new Item { Id = 3, Name = "name2" }
};

[EnableQuery]
public IQueryable<Item> Get()
{
return items.AsQueryable();
}

protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
}
}

According to the documentation this version of OData inherits from ODataController and [Queryable] represents an obsolete mark, that's why I use [EnableQuery]

4. In Models it was enough for me to replicate the solution to the question you are reacting (copying and pasting the IngoreNullEntityPropertiesSerializerProvider and IngoreNullEntityPropertiesSerializer classes in a new folder:

Sample Image

And the most difficult part, that of configuring the Serializer in WebApiConfig.cs:

public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Configuración y servicios de API web

// Rutas de API web
config.MapHttpAttributeRoutes();

config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);

config.MapODataServiceRoute("ODataRoute", null, b => b
.AddService(Microsoft.OData.ServiceLifetime.Singleton, typeof(IEdmModel), s => GetEdmModel())
.AddService(Microsoft.OData.ServiceLifetime.Singleton, typeof(IEnumerable<IODataRoutingConvention>), s => ODataRoutingConventions.CreateDefaultWithAttributeRouting("ODataRoute", config))
.AddService(Microsoft.OData.ServiceLifetime.Singleton, typeof(ODataSerializerProvider), sp => new IngoreNullEntityPropertiesSerializerProvider(sp))
);
}

private static IEdmModel GetEdmModel()
{
ODataConventionModelBuilder builder = new ODataConventionModelBuilder();

builder.EntitySet<Item>("Items");

return builder.GetEdmModel();
}
}

Finally the output of the Api:

Input:

public static List<Item> items = new List<Item>()
{
new Item { Id = 1, Name = "name1", OptionalField = "Value Present" },
new Item { Id = 3, Name = "name2" }
};

Sample Image

and with values:

Input:

public static List<Item> items = new List<Item>()
{
new Item { Id = 1, Name = "name1", OptionalField = "Value Present" },
new Item { Id = 3, Name = "name2", OptionalField = "Value Present2" }
};

Sample Image

I hope this has been helpful.

Ignore property when null using the new Net Core 3.0 Json

This was fixed on .Net 5

[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]

See the updates below

https://github.com/dotnet/runtime/issues/41313

https://github.com/dotnet/runtime/issues/30687

WebAPI: Null values not suppressed by Default XML Serializer

This declarative tag - [XmlElement(IsNullable = false)] - is honored by the XmlSerializer, but ignored by the DataContractSerializer. If you want to use this tag you need to explicitly select the XmlSerializer. As follows:

public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services

...

config.Formatters.XmlFormatter.UseXmlSerializer = true;

...

}
}


Related Topics



Leave a reply



Submit