Vicky
Vicky

Reputation: 734

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.

Upvotes: 3

Views: 5618

Answers (3)

ElasticCode
ElasticCode

Reputation: 7865

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 }

Upvotes: 6

Shiraj Momin
Shiraj Momin

Reputation: 685

public class Sample 
{
    [DataMember(EmitDefaultValue = false, IsRequired = false)]
    public string Test { get; set; }
}

Upvotes: 1

Vikas Chaturvedi
Vikas Chaturvedi

Reputation: 74

You can create custom converter by extending Newtonsoft.Json.JsonConverter and override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)

Upvotes: 0

Related Questions