I know that this was answered before, but since I have a very concise way (code) to serialize IDictionary with the DataContractSerializer class (used by WCF, but it can and should be used anywhere), I could not resist it here :
public static class SerializationExtensions { public static string Serialize<T>(this T obj) { var serializer = new DataContractSerializer(obj.GetType()); using (var writer = new StringWriter()) using (var stm = new XmlTextWriter(writer)) { serializer.WriteObject(stm, obj); return writer.ToString(); } } public static T Deserialize<T>(this string serialized) { var serializer = new DataContractSerializer(typeof(T)); using (var reader = new StringReader(serialized)) using (var stm = new XmlTextReader(reader)) { return (T)serializer.ReadObject(stm); } } }
This works fine in .NET 4, and should also work in .NET 3.5, although I have not tested it yet.
UPDATE:. does not work in the .NET Compact Framework (not even NETCF 3.7 for Windows Phone 7), because DataContractSerializer
not supported!
I made the stream into a string because it was more convenient for me, although I could introduce lower level serialization for Stream and then use it to serialize for strings, but I tend to generalize only when necessary (as premature optimization is evil , so premature generalization ...)
Using is very simple:
// dictionary to serialize to string Dictionary<string, object> myDict = new Dictionary<string, object>(); // add items to the dictionary... myDict.Add(...); // serialization is straight-forward string serialized = myDict.Serialize(); ... // deserialization is just as simple Dictionary<string, object> myDictCopy = serialized.Deserialize<Dictionary<string,object>>();
myDictCopy will be a verbatim copy of myDict.
You will also notice that the generic methods provided will be able to serialize any type (as far as I know), since it is not limited to IDictionary interfaces, it can really be any generic type T.
Hope this helps someone!
Loudenvier May 09 '11 at 18:49 2011-05-09 18:49
source share