DataContractSerializer and Dictionary<string,object> fails when reading
Try using the KnownTypeAttribute so that DataContractSerializer
knows about the List<string>
type. Unfortunately, that seems to go against your idea of not having to know about the types before hand.
I'm basing this on the following code, which uses DataContractSerializer
to serialize a Dictionary<string, object>
containing 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();
If you knownTypes
is not provided to the DataContractSerializer
, it throws an exception.
SerializationException: Type 'System.Collections.Generic.List`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]' with data contract name 'ArrayOfstring:http://schemas.microsoft.com/2003/10/Serialization/Arrays' is not expected. Consider using a DataContractResolver or add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.