Use JsonIgnore on certain inherited properties
Asked Answered
M

0

7

I have a base class like this-ish:

public class Baseclass
{
   public string Id { get; set; }
   public string Type { get; set; }
   public string Name { get; set; }
}

...and many classes that inherit these properties, like this-ish:

   public class Thing: Baseclass
    {
     public string Size{ get; set; }
     public string Color{ get; set; }
     public string Smell{ get; set; }
    }

Now, I don't want to serialize all of these properties (mvc/jsonresult), so I use [JsonIgnore] on the properties of a class I want to exclude, and that works fine. The problem is that I don't want to serialize all the inherited properties for a class either. I've asked around and gotten the following answer:

Ex: I don't want to serialize the inherited Id from Baseclass in Thing.

I should make Id in Baseclass virutal:

public virtual string Id { get; set; }

and add the following to the Thing class:

[JsonIgnore]
public override string Id { get; set; }

...but this doesn't work, I'm afraid. I can get around it rebuilding the class hierarchy. but I would prefer a simpler solution. Any suggestions as to why this solution didn't work or alternatives to exclude certain inherited properties?

Marduk answered 31/5, 2016 at 12:21 Comment(5)
Why do you not want to serialize it? If the derived class does not need that property then it sounds like it shouldn't be in your base class.Seamus
You can try this workaroundSyndicate
When I apply the [JsonIgnore] attribute to the "Id" property it does not serialize or de-serialize. I must be missing something: var x = new Thing() { Id = "1", Type = "2", Name = "3", Size = "4", Color = "5", Smell = "6" }; var y = JsonConvert.SerializeObject(x); var z = JsonConvert.DeserializeObject<Thing>(y);Christ
Some suggestions here: Ignore Base Class Properties in Json.NET Serialization. [JsonObject(MemberSerialization.OptIn)] looks like the easiest solution. In fact, is this a duplicate?Baedeker
Thanks for the replies! Some of the solutions are pretty close, but after some discussion with my co-worker, we have decided to rewrite the classes to avoid redundant properties instead, less messy.Marduk

© 2022 - 2024 — McMap. All rights reserved.