I am using Newtonsoft JSON serializer, and the serialized string is missing the properties from the derived class if the class is derived from a list. Here is my example code.
Classes:
[DataContract]
public class TestItem
{
[DataMember]
public int itemInt;
[DataMember]
public string itemString;
public TestItem() {}
public TestItem(int _intVal, string _stringVal)
{
itemInt = _intVal;
itemString = _stringVal;
}
}
[DataContract]
public class TestMain : List<TestItem>
{
[DataMember]
public int mainInt;
[DataMember]
public string mainString;
}
Serializing code:
string test;
// Test classes
TestMain main = new TestMain();
main.mainInt = 123;
main.mainString = "Hello";
main.Add(new TestItem(1, "First"));
test = Newtonsoft.Json.JsonConvert.SerializeObject(main);
After serialization, the value of test is:
[{\"itemInt\":1,\"itemString\":\"First\"}]
The values for mainInt and mainString are missing altogether.
The behaviour is not changed by the [DataContract] and [DataMember] tags, but I have them in there, to pre-empt the answer that they are missing.
How do I get JSON to recognize and serialize the mainInt and mainString properties of the derived class?