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.
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; }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With