3

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.

3
  • What do you mean by "ignore"? Commented May 2, 2018 at 7:04
  • 2
    That's not JSON. Commented May 2, 2018 at 7:12
  • Your keys need to be enclosed in double quotes. And the empty value also needs to be in double quotes. Commented May 2, 2018 at 7:16

3 Answers 3

6

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 }
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.