Nowadays, NuGet packages make developer life easy. Today going to talk more about Newtonsoft.Json NuGet package one of the feature.
Many times developer, don't want all fields to be serialize and part of that string which fields value as Null.
Because of nowadays developer playing JSON string to object and object to JSON string and its common.
Some time such requirement like only those fields need to save in JSON string which have values.
JSON property support to ignore the fields run time. which value has Null.
How to use JsonProperty(NullValueHandling = NullValueHanding.Ignore)
Json string only produced the Id and Name fields as output JSON string and ignore NickName field.
Many times developer, don't want all fields to be serialize and part of that string which fields value as Null.
Because of nowadays developer playing JSON string to object and object to JSON string and its common.
Some time such requirement like only those fields need to save in JSON string which have values.
JSON property support to ignore the fields run time. which value has Null.
class Client { public int Id { get; set; } public string Name { get; set; } [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] public string NickName { get; set; } }
How to use JsonProperty(NullValueHandling = NullValueHanding.Ignore)
Client client = new Client { Id = 1, Name = "Kalpesh", NickName = null, }; string json = JsonConvert.SerializeObject(client );JSON output string look like
{Id:1,Name:"Kalpesh"}Check the output JSON string and get better idea about the NickName field.
Json string only produced the Id and Name fields as output JSON string and ignore NickName field.