Last active
August 29, 2015 14:05
-
-
Save jltrem/12d03013e744b985d8d3 to your computer and use it in GitHub Desktop.
serializing IDictionary via XmlSerializer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <summary> | |
/// System.Collections.Generic.KeyValuePair has not setters so we have to roll our own in order to serialize. | |
/// </summary> | |
[Serializable] | |
[XmlType(TypeName = "KVP")] | |
public struct SerializableKeyValuePair<K, V> | |
{ | |
public K Key { get; set; } | |
public V Value { get; set; } | |
} | |
public static class DictionaryExt | |
{ | |
public static SerializableKeyValuePair<object, object>[] ToSerializableKeyValuePairs(this IDictionary dict) | |
{ | |
var list = new List<SerializableKeyValuePair<object, object>>(); | |
if (dict != null) | |
{ | |
foreach (DictionaryEntry entry in dict) | |
{ | |
list.Add(new SerializableKeyValuePair<object, object> { Key = entry.Key, Value = entry.Value }); | |
} | |
} | |
return list.ToArray(); | |
} | |
public static void FromSerializableKeyValuePairs(this IDictionary dict, IEnumerable<SerializableKeyValuePair<object, object>> items) | |
{ | |
if (items != null) | |
{ | |
foreach (var pair in items) | |
{ | |
dict.Add(pair.Key, pair.Value); | |
} | |
} | |
} | |
} | |
// and then to use ... | |
private OrderedDictionary _myDictionary; | |
[XmlIgnore] | |
public OrderedDictionary MyDictionary | |
{ | |
get { return _myDictionary ?? (_myDictionary = new OrderedDictionary()); } | |
set { _myDictionary = value; } | |
} | |
/// <summary> | |
/// Proxy to provide XML serialization of MyDictionary. | |
/// </summary> | |
[XmlElement("MyDictionary")] | |
public SerializableKeyValuePair<object, object>[] MyDictionaryXmlProxy | |
{ | |
get | |
{ | |
return MyDictionary.ToSerializableKeyValuePairs(); | |
} | |
set | |
{ | |
MyDictionary = new OrderedDictionary(); | |
MyDictionary.FromSerializableKeyValuePairs(value); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment