How to Ignoring Fields and Properties Conditionally During Serialization Using JSON.Net?
I can't inherit from JsonIgnoreAttribute
because it's a sealed
class. What should I do?
Asked
Active
Viewed 6,025 times
15

Mohamad Shiralizadeh
- 8,329
- 6
- 58
- 93
-
Did you check [ScriptIgnore](http://stackoverflow.com/questions/10169648/how-to-exclude-property-from-json-serialization) ? – Kurubaran Dec 16 '15 at 05:46
-
@Kurubaran yes but I want to Ignoring a Field Conditionally.. – Mohamad Shiralizadeh Dec 16 '15 at 05:52
2 Answers
18
You can use JSON.NET's ShouldSerialize-syntax. There's a good example on JSON.NET site:
http://www.newtonsoft.com/json/help/html/ConditionalProperties.htm
public class Employee
{
public string Name { get; set; }
public Employee Manager { get; set; }
public bool ShouldSerializeManager()
{
// don't serialize the Manager property if an employee is their own manager
return (Manager != this);
}
}
If ShouldSerialize doesn't fit your needs, you can take full control of the serialization with the ContractResolvers: http://www.newtonsoft.com/json/help/html/ContractResolver.htm

Mikael Koskinen
- 12,306
- 5
- 48
- 63
-
2Never had any luck getting this to work, breakpoints show that this is never even called during serialization. – Wobbles Apr 07 '16 at 23:01
-
Note that the ShouldSerialize-syntax is a convention such that for property Foo, you'd have a ShouldSerializeFoo() method, which would return a true or false as to whether Foo should be serialized. – CharlieNoTomatoes May 30 '17 at 19:54
2
I found the answer. I inherit from JsonConverter
and create a new convertor.
public class CustomJsonConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var list = (IList)value;
JArray s = new JArray();
foreach (var item in list)
{
JToken token = JToken.FromObject(item);
JObject obj = new JObject();
foreach (JProperty prop in token)
{
if (prop.Name != "Title") // your logic here
obj.Add(prop);
}
s.Add(obj);
}
s.WriteTo(writer);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException("Unnecessary because CanRead is false. The type will skip the converter.");
}
public override bool CanRead
{
get { return false; }
}
public override bool CanConvert(Type objectType)
{
return objectType != typeof(IList);
}
}

Mohamad Shiralizadeh
- 8,329
- 6
- 58
- 93