Update: solved! It seems like Json.NET does include derived type properties by default, but they were not included because of an error in my code where the derived type was overwritten by a base type.
I am currently working on a project for school, and I stumbled upon a problem.
I need to serialize an object to Json, which I do using Newtonsoft Json.NET. The object I am trying to serialize has a List of objects of a certain base class, but the objects in that List are of derived types with their own unique properties.
Currently, only the properties of the base class are included in the resulting Json. If it's possible, I'd like the Json converter to detect of which derived class the objects in the collection are, and to serialize their unique properties.
Below some code as an example of what I'm doing.
Classes I use:
public class WrappingClass
{
public string Name { get; set; }
public List<BaseClass> MyCollection { get; set; }
}
public class BaseClass
{
public string MyProperty { get; set; }
}
public class DerivedClassA : BaseClass
{
public string AnotherPropertyA { get; set; }
}
public class DerivedClassB : BaseClass
{
public string AnotherPropertyB { get; set; }
}
Serializing some dummy objects:
WrappingClass wrapperObject = new WrappingClass
{
Name = "Test name",
MyCollection = new List<BaseClass>();
};
DerivedClassA derivedObjectA = new DerivedClassA
{
MyProperty = "Test my MyProperty A"
AnotherPropertyA = "Test AnotherPropertyA"
};
DerivedClassB derivedObjectB = new DerivedClassB
{
MyProperty = "Test my MyProperty B"
AnotherPropertyB = "Test AnotherPropertyB"
};
wrapperObject.MyCollection.Add(derivedObjectA);
wrapperObject.MyCollection.Add(derivedObjectB);
var myJson = JsonConvert.SerializeObject(wrapperObject);
The Json that would currently be generated:
{"Name":"Test name","MyCollection":[{"MyProperty":"Test my MyProperty A"}{"MyProperty":"Test my MyProperty B"}]}
The Json I want:
{"Name":"Test name","MyCollection":[{"MyProperty":"Test my MyProperty A","AnotherPropertyA":"Test AnotherPropertyA"},{"MyProperty":"Test my MyProperty B","AnotherPropertyB":"Test AnotherPropertyB"}]}
Any ideas? Thank you!
[DataContract] [DataMember] [("jsonpropert....")]
ect if so please include them. – evanmcdonnal