读取时,DataContractSerializer和Dictionary <string,object>失败

Chr*_*rth 7 .net c# generics datacontractserializer

我正在使用DataContractSerializer序列化包含Dictionary<string,object>成员的对象,该成员标有[DataMember()].我们的想法是拥有一个灵活的对象属性包,我不知道这些属性是什么.

当我把这个伟大的工程int,doublestring对象到字典中,但是当我把List<string>它未能反序列化对象有:

System.InvalidOperationException: Node type Element is not supported in this operation.
Run Code Online (Sandbox Code Playgroud)

整个字典被序列化为XML,看起来很合理:

<Attributes xmlns:d2p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
    <d2p1:KeyValueOfstringanyType>
        <d2p1:Key>name</d2p1:Key>
        <d2p1:Value xmlns:d4p1="http://www.w3.org/2001/XMLSchema" i:type="d4p1:string">Test object</d2p1:Value>
    </d2p1:KeyValueOfstringanyType>
    <d2p1:KeyValueOfstringanyType>
        <d2p1:Key>x</d2p1:Key>
        <d2p1:Value xmlns:d4p1="http://www.w3.org/2001/XMLSchema" i:type="d4p1:double">0.5</d2p1:Value>
    </d2p1:KeyValueOfstringanyType>
    <d2p1:KeyValueOfstringanyType>
        <d2p1:Key>y</d2p1:Key>
        <d2p1:Value xmlns:d4p1="http://www.w3.org/2001/XMLSchema" i:type="d4p1:double">1.25</d2p1:Value>
    </d2p1:KeyValueOfstringanyType>
    <d2p1:KeyValueOfstringanyType>
        <d2p1:Key>age</d2p1:Key>
        <d2p1:Value xmlns:d4p1="http://www.w3.org/2001/XMLSchema" i:type="d4p1:int">4</d2p1:Value>
    </d2p1:KeyValueOfstringanyType>
    <d2p1:KeyValueOfstringanyType>
        <d2p1:Key>list-of-strings</d2p1:Key>
        <d2p1:Value>
            <d2p1:string>one string</d2p1:string>
            <d2p1:string>two string</d2p1:string>
            <d2p1:string>last string</d2p1:string>
        </d2p1:Value>
    </d2p1:KeyValueOfstringanyType>
</Attributes>
Run Code Online (Sandbox Code Playgroud)

请注意list-of-strings那里的结尾.它有所有的价值,但没有任何迹象表明它是一个List<string>或任何东西.

处理这种情况的正确方法是什么?

Jef*_*ata 9

尝试使用KnownTypeAttribute以便DataContractSerializer了解List<string>类型.不幸的是,这似乎违背了你不必事先知道类型的想法.

我基于以下代码,它用于DataContractSerializer序列化Dictionary<string, object>包含List<string>:

Dictionary<string,object> dictionary = new Dictionary<string, object>();

dictionary.Add("k1", new List<string> { "L1", "L2", "L3" });

List<Type> knownTypes = new List<Type> { typeof(List<string>) };
DataContractSerializer serializer = new DataContractSerializer(typeof(Dictionary<string,object>), knownTypes);
MemoryStream stream = new MemoryStream();

serializer.WriteObject(stream, dictionary);

StreamReader reader = new StreamReader(stream);

stream.Position = 0;
string xml = reader.ReadToEnd();
Run Code Online (Sandbox Code Playgroud)

如果knownTypes未向您提供DataContractSerializer,则会引发异常.

SerializationException:键入'System.Collections.Generic.List`1 [[System.String,mscorlib,Version = 4.0.0.0,Culture = neutral,PublicKeyToken = b77a5c561934e089]]',数据协定名称为"ArrayOfstring:http:// schemas".预计不会出现microsoft.com/2003/10/Serialization/Arrays'.考虑使用DataContractResolver或将任何静态未知的类型添加到已知类型列表中 - 例如,通过使用KnownTypeAttribute属性或将它们添加到传递给DataContractSerializer的已知类型列表中.