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?

5
  • 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. Commented May 31, 2016 at 12:36
  • 1
    You can try this workaround Commented May 31, 2016 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<Thing>(y); Commented May 31, 2016 at 12:54
  • 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? Commented Jun 1, 2016 at 7: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. Commented Jun 9, 2016 at 11:02

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.