Ignore null and default value from serializer in web api

I want to ignore this property from Json serialization, which is null. for this, I added this line to my webapi.config file.

 config.Formatters.JsonFormatter.SerializerSettings = new JsonSerializerSettings {NullValueHandling = NullValueHandling.Ignore}; public static void Register(HttpConfiguration config) { config.SuppressDefaultHostAuthentication(); config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType)); config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{action}/{identifier}", defaults: new { identifier = RouteParameter.Optional } ); config.Formatters.JsonFormatter.SerializerSettings = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore, DefaultValueHandling= DefaultValueHandling.Ignore }; } 

But this does not ignore those properties that are null.

This is my class

 public class UserProfile { [JsonProperty("fullname")] public string FullName { get; set; } [JsonProperty("imageid")] public int ImageId { get; set; } [JsonProperty("dob")] public Nullable<DateTime> DOB { get; set; } } 

This is Json return from web api

  { "fullname": "Amit Kumar", "imageid": 0, "dob": null } 

I did not assign a value to dob and imageid.

I follow this link , but this did not solve my problem.

+5
source share
1 answer

Looking at the source code for Newtonsoft.Json, I believe that the JsonPropertyAttribute decorating your class properties overrides the default NullValueHandling specified in the JsonSerializerSettings .

Either remove such an attribute (if you want to use the globally defined NullValueHandling), or explicitly specify NullValueHandling :

 public class UserProfile { [JsonProperty("fullname")] public string FullName { get; set; } [JsonProperty("imageid")] public int ImageId { get; set; } [JsonProperty("dob", NullValueHandling = NullValueHandling.Ignore)] public Nullable<DateTime> DOB { get; set; } } 
0
source

Source: https://habr.com/ru/post/1246867/


All Articles