public class AppConfig
{
public SerializableDictionary Dictionary1;
public SerializableDictionary Dictionary2;
}public SerializableDictionary
Attempt to serialize the above class will fail with a System.InvalidOperationException: Two mapping for dictionary. Searching the web for the exact error message returns no useful result, except for a posting which described a similiar problem (Two mappings for SourceTree.DTO.InventoryItemCollection.) but did not provide a solution. The posting also explicitly mentioned that the error occurred only on .NET Compact Framework, and not on the full framework.
The root cause of the error is at the first few lines of the SerializableDictionary source code:
[XmlRoot("dictionary")]
public class SerializableDictionary: Dictionary
With this declaration, when 2 SerializableDictionary stay in the same class (which will be serialized), there will perhaps be a conflict somewhere as both of them are set up to use the same XmlRoot element ("dictionary").
A workaround is not to define XmlRoot inside SerializableDictionary class, but to create another class inheriting from SerializableDictionary and define XmlRoot in this class:
//parent class: SerializableDictionary
public class SerializableDictionary
: Dictionary, IXmlSerializable { .... }
: Dictionary
//dictionary 1
[XmlRoot("SerializableDictionary1")]
public class SerializableDictionary1 : SerializableDictionary { }
//dictionary 2
[XmlRoot("SerializableDictionary2")]
public class SerializableDictionary2 : SerializableDictionary { }
//the class to be serialized
public class AppConfigNew
{
public SerializableDictionary1 Dictionary1;
public SerializableDictionary2 Dictionary2;
public SerializableDictionary2
}
This requires a few more lines of code, but is the cleanest workaround I have found. Also, I have yet to figure out why the full framework does not have such a problem.
Thanks man, that is what i was looking for.
ReplyDeleteIt was very helpful
Vidhya
Vidhya, glad that my suggestions helped you :)
ReplyDelete