Deserializing xml to object with dictionary

前端 未结 5 846

This is my class structure:

class DataItem
{
   public string Id { get; set; }
   public string Type { get; set; }

   private Dictionary

        
5条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-25 19:00

    I know this has been answered before, but since I have a very concise way (code) for doing IDictionary serialization with the DataContractSerializer class (used by WCF, but could and should be used anywhere) I couldn't resist contributing it here:

    public static class SerializationExtensions
    {
        public static string Serialize(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(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 perfectly in .NET 4 and should also work in .NET 3.5, although I didn't test it yet. I did the streaming to string because it was more convenient to me, although I could have introduced a lower-level serialization to Stream and then used it to serialize to strings, but I tend to generalize only when needed (just like premature optimization is evil, so it is premature generalization...)

    Usage is very simple:

    // dictionary to serialize to string
    Dictionary myDict = new Dictionary();
    // add items to the dictionary...
    myDict.Add(...);
    // serialization is straight-forward
    string serialized = myDict.Serialize();
    ...
    // deserialization is just as simple
    Dictionary myDictCopy = 
        serialized.Deserialize>();
    

    myDictCopy will be a verbatim copy of myDict.

    You'll also notice that the generic methods provided will be able to serialize any type (to the best of my knowledge) since it is not limited to IDictionary interfaces, it can be really any generic type T.

    Hope it helps someone out there!

提交回复
热议问题