I have data that is best described as “look like onions,” since each outer layer is built on what's below it. Below you will see a significantly simplified version (I have several levels deeper, but they exhibit the same behavior at each level).
[CollectionDataContract] public abstract class AbstractTestGroup : ObservableCollection<AbstractTest> { [DataMember] public abstract string Name { get; set; } } [CollectionDataContract] [KnownType(typeof(Test))] public class TestGroup : AbstractTestGroup { public override string Name { get { return "TestGroupName"; } set { } } [DataMember] public string Why { get { return "Why"; } set { } } } [DataContract] public abstract class AbstractTest { [DataMember] public abstract string SayHello { get; set; } } [DataContract] public class Test : AbstractTest {
I create an instance of TestGroup and add Test objects to it using the .Add that comes with the ObservableCollection .
When I serialize and de-serialize this structure, I get the following
<TestGroup xmlns="http://schemas.datacontract.org/2004/07/WpfApplication2" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"> <AbstractTest i:type="Test"> <SayHello>HELLO</SayHello> <Month>June</Month> </AbstractTest> </TestGroup>
The output is disconnected from the DataMember in the TestGroup . As I get deeper in my bow, DataMember that are higher (even from abstract classes) are not included. I tried adding [KnownType(typeof(TestGroup))] to TestGroup and AbstractTestGroup without success.
Question: Why can't I serialize the DataMember Why in the TestGroup class?
Next question: Is there an alternative way to serialize and de-serialize the structure of this figure? I plan to use the output locally to “load” the configuration that the user specifies. I would prefer not to specify my own Serialization scheme if I can avoid it.
For those interested here, I create a class by serializing it and de-serializing it.
TestGroup tg = new TestGroup(); tg.Add(new Test()); DataContractSerializer ser = new DataContractSerializer(typeof(TestGroup)); MemoryStream memoryStream = new MemoryStream(); ser.WriteObject(memoryStream, tg); memoryStream.Seek(0, SeekOrigin.Begin); string str; using (StreamReader sr = new StreamReader(memoryStream)) str = sr.ReadToEnd();
Edit:. Why did I try to switch to using Serializable instead and have the same problem.