通常はシリアル化されているクラスを逆シリアル化しようとしています。
public class MyClass
{
private List<Section> sections = new List<Section>();
public List<Section> Sections
{
get
{
return this.sections;
}
}
}
public class Section1: Section
{
public string MyProperty {get;set;}
}
public class Section2 : Section
{
public string MyProperty2 {get;set;}
}
クラスMyClassをエラーなしでシリアル化しましたが、逆シリアル化しようとすると、セクションに空のプロパティを持つクラスMyClassが表示されました(このプロパティは空でした)。
これはなぜですか、この問題を解決する方法は?
xmlの例:
<MyClass>
<Sections>
<Section1>
<MyProperty>foo1</MyProperty>
</Section1>
<Section1>
<MyProperty>foo2</MyProperty>
</Section1>
<Section2>
<MyProperty2>boo1</MyProperty2>
</Section2>
</Sections>
</MyClass>
コードのシリアル化と逆シリアル化:
シリアル化/逆シリアル化に使用されたクラス:
public class ObjectSerializer
{
private readonly XmlAttributeOverrides xmlAttributeOverrides = new XmlAttributeOverrides();
public void XmlSerialize<T>(T value, TextWriter outStream)
{
Type type = typeof (T);
object[] result = type.GetCustomAttributes(typeof (SerializableAttribute), true);
if (result != null)
{
var serializer = new XmlSerializer(type, this.xmlAttributeOverrides);
serializer.Serialize(outStream, value);
}
}
public T XmlDeserialize<T>(string xml)
{
var textReader = new XmlTextReader(new StringReader(xml));
var xmlSerializer = new XmlSerializer(typeof(T));
var result = xmlSerializer.Deserialize(textReader);
return (T)result;
}
public void ExportOverridesFrom<TAssemply, TBaseType, TObject>(
Expression<Func<TObject, object>> propertySelector)
{
IEnumerable<Type> inheritedTypes = typeof (TAssemply).Assembly.GetTypes().Where(t => t.BaseType == typeof (TBaseType));
var xmlAttributes = new XmlAttributes();
foreach (Type type in inheritedTypes)
{
var xmlElementAttribute = new XmlElementAttribute {Type = type};
xmlAttributes.XmlElements.Add(xmlElementAttribute);
}
PropertyInfo objectProperty = Reflect<TObject>.GetProperty(propertySelector);
this.xmlAttributeOverrides.Add(typeof (TObject), objectProperty.Name, xmlAttributes);
}
}
シリアル化:すべて良いです!
var objectSerializer = new ObjectSerializer();
objectSerializer.ExportOverridesFrom<Section1, Section, MyClass>(p => p.Sections);
objectSerializer.XmlSerialize(myClass, resultStream);
デシリアリザトイン:すべてが悪い!
xml - result serialization.
var result = objectSerializer.XmlDeserialize<MyClass>(xml);
ありがとう、オクサナ