6

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?

robertpaulsen
  • 209
  • 4
  • 9
  • 1
    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. – D Stanley May 31 '16 at 12:36
  • 1
    You can try [this](http://stackoverflow.com/questions/22638778/avoid-using-the-jsonignore-attribute-in-a-domain-model) workaround – Fabjan May 31 '16 at 12:36
  • 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(y);` – Ryan Peters May 31 '16 at 12:54
  • Some suggestions here: [Ignore Base Class Properties in Json.NET Serialization](https://stackoverflow.com/questions/31104335/ignore-base-class-properties-in-json-net-serialization). `[JsonObject(MemberSerialization.OptIn)]` looks like the easiest solution. In fact, is this a duplicate? – dbc Jun 01 '16 at 07:28
  • 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. – robertpaulsen Jun 09 '16 at 11:02

0 Answers0