I am using Newtonsoft's JsonSerializer to serialise some classes.
As I wanted to omit one field of my class in the serialisation process, I declared it as follow:
[JsonIgnore]
public int ParentId { get; set; }
This worked, but I am now facing a new problem : In a derived class, I would like this field to appear (and do so only in this specific derived class).
I have been looking through the documentation and on the Internet for a way to override this setting in child classes (I guess I need something like [JsonStopIgnore]
, but I couldn't find anything close).
JsonSerializer
to pick up again this attribute ?[JsonIgnore]
, but only in base class ?Yes, add prop. PropertyName = prop. UnderlyingName; inside the loop in the resolver. This will cause the property to use its original name.
Ignore individual properties You can specify conditional exclusion by setting the [JsonIgnore] attribute's Condition property. The JsonIgnoreCondition enum provides the following options: Always - The property is always ignored. If no Condition is specified, this option is assumed.
The only way to "override" the behavior of the [JsonIgnore]
attribute is to use a contract resolver, as @Yuval Itzchakov nicely explained in his answer.
However, there is another possible solution that might work for you: instead of using a [JsonIgnore]
attribute, you could implement a ShouldSerializeParentId()
method in your classes to control whether the ParentId
property gets serialized. In the base class, make this method return false
; then, override the method in the derived class to return true
. (This feature is known as conditional property serialization in Json.Net.)
public class Base
{
public int Id { get; set; }
public int ParentId { get; set; }
public virtual bool ShouldSerializeParentId()
{
return false;
}
}
public class Derived : Base
{
public override bool ShouldSerializeParentId()
{
return true;
}
}
Fiddle: https://dotnetfiddle.net/65sCSz
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With