序列化/反序列化派生类作为基类



例如,我有以下类:

public abstract class Device
{
}
public class WindowsDevice: Device
{
}
public class AndroidDevice: Device
{
}

现在我想将WindowsDevice和AndroidDevice序列化/反序列化为XML:

public static string Serialize(object o, Type[] additionalTypes = null)
{
var serializer = new XmlSerializer(o.GetType(), additionalTypes);
using (var stringWriter = new StringWriterWithEncoding(Encoding.UTF8))
{
serializer.Serialize(stringWriter, o);
return stringWriter.ToString();
}
}

这将产生以下输出:

<?xml version="1.0" encoding="utf-8"?>
<WindowsDevice xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
</WindowsDevice>

但是现在我无法反序列化它,因为在我的应用程序中我不知道XML是WindowsDevice还是AndroidDevice,所以我必须反序列化为typeof(Device)。但是,我将得到一个异常,即"WindowsDevice"在XML中是意外的。

我尝试了XmlInclude和extraType,但没有成功。

我不明白的是,如果我有以下示例类:

public class SampleClass
{
public List<Device> Devices {get;set}
}

如果我序列化 SampleClass 并使用 XmlInclude 或 extraType,我完全得到了我想要的:

<Devices>
<Device xsi:type="WindowsDevice"></Device>
</Devices>

但是我没有那个类,也没有设备列表。我只想序列化/反序列化WindowsDevice和AndroidDevice,但在反序列化时我不知道它是AndroidDevice还是WindowsDevice,所以我必须使用typeof(Device)并希望获得正确的Sublass AndroidDevice或WindowsDevice,所以而不是:

<WindowsDevice></WindowsDevice>

我想要:

<Device xsi:type="WindowsDevice"></Device>

如何做到这一点?

您的问题是您在序列化和反序列化期间构造XmlSerializer不一致。 在这两种情况下,您都需要使用相同的Type参数来构造它,特别是基类型typeof(Device)。 因此,我建议您用一种特定于Device的序列化方法替换现有的完全通用的序列化方法:

public static class DeviceExtensions
{
public static string SerializeDevice<TDevice>(this TDevice o) where TDevice : Device
{
// Ensure that [XmlInclude(typeof(TDevice))] is present on Device.
// (Included for clarity -- actually XmlSerializer will make a similar check.)
if (!typeof(Device).GetCustomAttributes<XmlIncludeAttribute>().Any(a => a.Type == o.GetType()))
{
throw new InvalidOperationException("Unknown device type " + o.GetType());
}
var serializer = new XmlSerializer(typeof(Device)); // Serialize as the base class
using (var stringWriter = new StringWriterWithEncoding(Encoding.UTF8))
{
serializer.Serialize(stringWriter, o);
return stringWriter.ToString();
}
}
public static Device DeserializeDevice(this string xml)
{
var serial = new XmlSerializer(typeof(Device));
using (var reader = new StringReader(xml))
{
return (Device)serial.Deserialize(reader);
}
}
}

然后,对所有可能的子类型[XmlInclude(typeof(TDevice))]应用于Device

[XmlInclude(typeof(WindowsDevice))]
[XmlInclude(typeof(AndroidDevice))]
public abstract class Device
{
}

然后,这两种类型的设备现在可以在保留其类型的同时成功序列化和反序列化,因为XmlSerializer将包含一个"xsi:type"属性来显式指示类型:

<Device xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:type="WindowsDevice" />

<Device xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:type="AndroidDevice" />

样品小提琴。

更新

所以问题是,我用typeof(WindowsDevice)而不是typeof(Device)序列化?

是的。

如果我必须使用typeof(WindowsDevice)的解决方案的任何想法?因为我有数百个类,不想使用数百个不同的 XmlSerializer 初始化......

这更像是一个架构问题,而不是一个如何解决的问题。 一种可能性是引入一个自定义属性,您可以将其应用于类,以指示该类的任何子类型应始终序列化为属性化基类型。 还需要所有适当的[XmlInclude(typeof(TDerivedType))]属性:

[System.AttributeUsage(System.AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
public class XmlBaseTypeAttribute : System.Attribute
{
}   
[XmlInclude(typeof(WindowsDevice))]
[XmlInclude(typeof(AndroidDevice))]
[XmlBaseType]
public abstract class Device
{
}

然后修改通用 XML 序列化代码以查找要序列化的对象的类型层次结构以获取[XmlBaseType]属性,并(取消)序列化为该类型:

public static class XmlExtensions
{
static Type GetSerializedType(this Type type)
{
var serializedType = type.BaseTypesAndSelf().Where(t => Attribute.IsDefined(t, typeof(XmlBaseTypeAttribute))).SingleOrDefault();
if (serializedType != null)
{
// Ensure that [XmlInclude(typeof(TDerived))] is present on the base type
// (Included for clarity -- actually XmlSerializer will make a similar check.)
if (!serializedType.GetCustomAttributes<XmlIncludeAttribute>().Any(a => a.Type == type))
{
throw new InvalidOperationException(string.Format("Unknown subtype {0} of type {1}", type, serializedType));
}
}
return serializedType ?? type;
}
public static string Serialize(this object o)
{
var serializer = new XmlSerializer(o.GetType().GetSerializedType());
using (var stringWriter = new StringWriterWithEncoding(Encoding.UTF8))
{
serializer.Serialize(stringWriter, o);
return stringWriter.ToString();
}
}
public static T Deserialize<T>(this string xml)
{
var serial = new XmlSerializer(typeof(T).GetSerializedType());
using (var reader = new StringReader(xml))
{
return (T)serial.Deserialize(reader);
}
}
}

当然,这意味着如果你的代码试图反序列化XML,它希望包含一个WindowsDevice,它实际上可能会根据XML的内容返回一个AndroidDevice

样本小提琴#2。

最新更新