Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ignore property if it is an empty ('') string from Json/Api Response C#

Below is the json response I have currently.

{
   firstName: "xyz",
   lastName: "efh",
   id: 123,
   key: ''
}

How to ignore a property if it is an empty string like key from the above response. I know how to ignore a a property when it is null but not when it is empty.

like image 499
Vicky Avatar asked Dec 01 '25 23:12

Vicky


2 Answers

To ignore empty string use default value handling option and set property default value to empty string

[DefaultValue("")]
public string key { get; set; }

And in set JsonSerializerSettings as below

new JsonSerializerSettings 
          { DefaultValueHandling = DefaultValueHandling.Ignore }
like image 79
ElasticCode Avatar answered Dec 03 '25 14:12

ElasticCode


public class Sample 
{
    [DataMember(EmitDefaultValue = false, IsRequired = false)]
    public string Test { get; set; }
}
like image 24
Shiraj Momin Avatar answered Dec 03 '25 13:12

Shiraj Momin