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?
Is this what you want?
[DataContract]
public class TestItem
{
[DataMember]
public int itemInt { get; set; }
[DataMember]
public string itemString { get; set; }
public TestItem() { }
public TestItem(int _intVal, string _stringVal)
{
itemInt = _intVal;
itemString = _stringVal;
}
}
[DataContract]
public class TestMain
{
[DataMember]
public int mainInt { get; set; }
[DataMember]
public string mainString { get; set; }
[DataMember]
public List<TestItem> TestItem = new List<TestItem>();
}
class Program
{
static void Main(string[] args)
{
string test;
// Test classes
TestMain main = new TestMain();
main.mainInt = 123;
main.mainString = "Hello";
main.TestItem.Add(new TestItem(1, "First"));
test = Newtonsoft.Json.JsonConvert.SerializeObject(main);
Console.WriteLine(test);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With