I have several classes that are derived from a base class. Base class properties have [DataMember] attribute but derived class properties don't have it. When I use JsonConvert.SerializeObject() on child class object, I see only properties in base class getting serialized unless I add [DataMember] to the property of derived class. How do I make SerializeObject() to serialize all properties of derived class including that of properties defined in base class by ignoring [DataMember] attribute? I want to avoid adding [DataMember] to all properties of derived class.
Asked
Active
Viewed 3,248 times
2
-
Did you ever find a solution to this? – BLAZORLOVER Aug 03 '22 at 22:38
1 Answers
-1
Without any actual code posted the source of your problem is hard to point out. Maybe you could just drop any de/serialization attributes, like [DataMember()]
or [JsonProperty()]
, and give it another try, since having
public abstract class Base
{
public abstract string BaseProp { get; }
}
public class MyBase : Base
{
public override string BaseProp { get { return "propA"; } }
public string MyBaseProp { get; set; }
}
public class My : MyBase
{
public string MyProp { get; set; }
}
And then serializing given class instances
var myBase = new MyBase { MyBaseProp = "prop1" };
Console.WriteLine(JsonConvert.SerializeObject(myBase));
var my = new My { MyBaseProp = "prop1", MyProp = "prop2" };
Console.WriteLine(JsonConvert.SerializeObject(my));
Gives you the following output
{"BaseProp":"propA","MyBaseProp":"prop1"}
{"MyProp":"prop2","BaseProp":"propA","MyBaseProp":"prop1"}

Mikko Viitala
- 8,344
- 4
- 37
- 62
-
1Irrelevant to the question, Questioner already knows how to handle serialize `Derived/Base` class, but looking for an optimum elegant way to unmask `Derived` classes' members. means **using less `[DataMember]` over each `Derived property`** – Rzassar Dec 17 '17 at 09:53