Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I "un-JsonIgnore" an attribute in a derived class?

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).


  • Is there any way for me to force JsonSerializer to pick up again this attribute ?
  • Is it possible to explicitly mark an attribute as [JsonIgnore], but only in base class ?
like image 815
PLNech Avatar asked Feb 23 '15 12:02

PLNech


People also ask

Can I optionally turn off the JsonIgnore attribute at runtime?

Yes, add prop. PropertyName = prop. UnderlyingName; inside the loop in the resolver. This will cause the property to use its original name.

What is JsonIgnore attribute?

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.


1 Answers

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

like image 82
Brian Rogers Avatar answered Nov 02 '22 03:11

Brian Rogers