Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ignore null and default value from serializer in web api

I want to Ignore those property from Json serializing which is null. for this I added this line in 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 It is not ignoring those property which is 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; }
    }

It is Json return from web api

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

I have not assigned the value of dob and imageid.

I follow this Link , but It didn't solve my problem.

like image 671
Amit Kumar Avatar asked Apr 11 '16 12:04

Amit Kumar


1 Answers

By looking at Newtonsoft.Json source code I believe that the JsonPropertyAttribute decorating your class properties is overriding the default NullValueHandling specified in JsonSerializerSettings.

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

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; }
}
like image 198
Federico Dipuma Avatar answered Oct 04 '22 21:10

Federico Dipuma