Have come across XML deserialization issue of class instances with List<byte> public properties when that properties have default definition in class constrictor


Say we have class:



public class TestClass
{
public List<byte> ByteList;
public TestClass()
{
this.ByteList = new List<byte>() { 0x01, 0x02 };
}
}


then we have following code to test serialization/deserialization



TestClass testClass = new TestClass();
Console.WriteLine("testClass.ByteList.Count: {0}", testClass.ByteList.Count);

System.Xml.Serialization.XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer(typeof(TestClass));
using (System.IO.FileStream fs = new System.IO.FileStream(@".\testClass.xml", System.IO.FileMode.OpenOrCreate))
{
xmlSerializer.Serialize(fs, testClass);
}
Console.WriteLine("testClass.ByteList.Count: {0}", testClass.ByteList.Count);

TestClass deserializedTestClass = null;
using (System.IO.FileStream sr = new System.IO.FileStream(@".\testClass.xml", System.IO.FileMode.Open))
{
deserializedTestClass = (TestClass)xmlSerializer.Deserialize(sr);
}
Console.WriteLine("deserializedTestClass.ByteList.Count: {0}", deserializedTestClass.ByteList.Count);


as a result we see on console following output:



testClass.ByteList.Count: 2


testClass.ByteList.Count: 2


deserializedTestClass.ByteList.Count: 4



serialization result xml is here:



<?xml version="1.0"?>
<TestClass xmlns:xsi="http://ift.tt/ra1lAU" xmlns:xsd="http://ift.tt/tphNwY">
<ByteList>
<unsignedByte>1</unsignedByte>
<unsignedByte>2</unsignedByte>
</ByteList>
</TestClass>


Could somebody explain what is going on here and how to fix it?


No comments:

Post a Comment