6

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.

Community
  • 1
  • 1
Amit Kumar
  • 5,888
  • 11
  • 47
  • 85

1 Answers1

1

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; }
}
Federico Dipuma
  • 17,655
  • 4
  • 39
  • 56
  • I removed those JsonProperty, But still the problem is same. – Amit Kumar Apr 11 '16 at 16:06
  • It's truly a strange behavior. I tried to reproduce the issue in a new web API project, but everything is working fine. With current information I do not have any clue about what could be wrong. Try adding the content of your Startup.cs or Global.asax.cs file to the question. – Federico Dipuma Apr 12 '16 at 12:39