Search code examples
c#xmldictionarydatacontractserializer

Error deserializing Dictionary<TKey,TValue> after changes on class TKey


If been serializing a generic dictionary, straightforward like this:

using (Stream stream = File.Open(fileName, FileMode.OpenOrCreate, FileAccess.Write))
{
    var writer = XmlWriter.Create(stream, new XmlWriterSettings { Indent = true });
    var objectType = typeof(T);
    var serializer = new DataContractSerializer(objectType);
    serializer.WriteObject(writer, objectToSerialize);
    writer.Close();
}

where T is Dictionary<DataSource, bool>. DataSource is a custom type. Now I worked on the class DataSource and made some changes, without changing the DataContract or properties involved in serialization.

Now, I a cannot deserialize the XML anymore and get the following exception:

Error in line 1 position 163. Expecting element 'ArrayOfKeyValueOfDataSourcebooleanClMIOMsG' from namespace 'http://schemas.microsoft.com/2003/10/Serialization/Arrays'.. Encountered 'Element' with name 'ArrayOfKeyValueOfDataSourcebooleandM5BGXus', namespace 'http://schemas.microsoft.com/2003/10/Serialization/Arrays'.

My questions are:

  • Where does the ID in the type name come from ("CIMIOMsG')?
  • Why did it change?
  • What can I do to deserialize my old files?

Solution

  • Found the mistake: I changed the namespace of the class DataSource (must have been a reflex triggered by ReSharper...). Changing the namespace to the original version fixed it. The id seems to be a namespace hash.