1

There is a C# class which has certain properties. When outputting an object of this class in a HttpResponseMessage, I know that if a property is null, we can hide that property in JSON response by annotating that property with the following

[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]

Is there a way to hide the same property if its a certain value? For e.g. dont show SportType property in JSON if its value is "Tennis"?

blue piranha
  • 3,706
  • 13
  • 57
  • 98

2 Answers2

2

In JSON.net you are be able to use conditional conditional property serialization

public class Foo
{
    public string Id {get; set;}
    public SomeProperty Name { get; set; }    

    public bool ShouldSerializeSomeProperty()
    {
        return SomeProperty != null || SomeProperty != "Tennis";
    }
}

You can define conditional methods for each property you like to define conditional serializing. For example in ShouldSerializeSomeProperty, I defined a condition for SomeProperty property.

Ali Bahrami
  • 5,935
  • 3
  • 34
  • 53
2

You could use ShouldSerializeX method to ignore serialization of property depends on some condition.

public class SampleJsonClass
{
    public int Id { get; set; }
    public string Name { get; set; }

    public bool ShouldSerializeName()
    {
        return (Name != "Tennis");
    }
}

Then

var list = new List<SampleJsonClass>()
{
    new SampleJsonClass() {Id = 1, Name = "Sample"},
    new SampleJsonClass() {Id = 1, Name = "Tennis"}
};
var serializedJson = JsonConvert.SerializeObject(list);

Output

[
   {
      "Id":1,
      "Name":"Sample"
   },
   {
      "Id":1
   }
]
lucky
  • 12,734
  • 4
  • 24
  • 46