如何使用Dictionary <string,object>属性?</string,object>序列化对象

时间:2010-01-13 11:03:33

标签: c# serialization dictionary xml-serialization

在下面的示例代码中,我收到了错误

  

元素   TestSerializeDictionary123.Customer.CustomProperties   vom Typ   System.Collections.Generic.Dictionary`2 [System.String,   mscorlib,版本= 2.0.0.0,   文化=中性,   公钥= b77a5c561934e089],[System.Object的,   mscorlib,版本= 2.0.0.0,   文化=中性,   PublicKeyToken = b77a5c561934e089]]可以   不被序列化,因为它   实现IDictionary。

当我取出Dictionary属性时,它可以精细

如何使用字典属性序列化此Customer对象?或者我可以使用哪种替换类型的词典可以序列化?

using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.IO;
using System.Xml;
using System.Text;

namespace TestSerializeDictionary123
{
    public class Program
    {
        static void Main(string[] args)
        {
            List<Customer> customers = Customer.GetCustomers();

            Console.WriteLine("--- Serializing ------------------");

            foreach (var customer in customers)
            {
                Console.WriteLine("Serializing " + customer.GetFullName() + "...");
                string xml = XmlHelpers.SerializeObject<Customer>(customer);
                Console.WriteLine(xml);
                Console.WriteLine("Deserializing ...");
                Customer customer2 = XmlHelpers.DeserializeObject<Customer>(xml);
                Console.WriteLine(customer2.GetFullName());
                Console.WriteLine("---");
            }

            Console.ReadLine();
        }
    }

    public static class StringHelpers
    {
        public static String UTF8ByteArrayToString(Byte[] characters)
        {
            UTF8Encoding encoding = new UTF8Encoding();
            String constructedString = encoding.GetString(characters);
            return (constructedString);
        }

        public static Byte[] StringToUTF8ByteArray(String pXmlString)
        {
            UTF8Encoding encoding = new UTF8Encoding();
            Byte[] byteArray = encoding.GetBytes(pXmlString);
            return byteArray;
        }
    }

    public static class XmlHelpers
    {
        public static string SerializeObject<T>(object o)
        {
            MemoryStream ms = new MemoryStream();
            XmlSerializer xs = new XmlSerializer(typeof(T));
            XmlTextWriter xtw = new XmlTextWriter(ms, Encoding.UTF8);
            xs.Serialize(xtw, o);
            ms = (MemoryStream)xtw.BaseStream;
            return StringHelpers.UTF8ByteArrayToString(ms.ToArray());
        }

        public static T DeserializeObject<T>(string xml)
        {
            XmlSerializer xs = new XmlSerializer(typeof(T));
            MemoryStream ms = new MemoryStream(StringHelpers.StringToUTF8ByteArray(xml));
            XmlTextWriter xtw = new XmlTextWriter(ms, Encoding.UTF8);
            return (T)xs.Deserialize(ms);
        }
    }

    public class Customer
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Street { get; set; }
        public string Location { get; set; }
        public string ZipCode { get; set; }
        public Dictionary<string,object> CustomProperties { get; set; }

        private int internalValue = 23;

        public static List<Customer> GetCustomers()
        {
            List<Customer> customers = new List<Customer>();
            customers.Add(new Customer { Id = 1, FirstName = "Jim", LastName = "Jones", ZipCode = "23434" });
            customers.Add(new Customer { Id = 2, FirstName = "Joe", LastName = "Adams", ZipCode = "12312" });
            customers.Add(new Customer { Id = 3, FirstName = "Jack", LastName = "Johnson", ZipCode = "23111" });
            customers.Add(new Customer { Id = 4, FirstName = "Angie", LastName = "Reckar", ZipCode = "54343" });
            customers.Add(new Customer { Id = 5, FirstName = "Henry", LastName = "Anderson", ZipCode = "16623" });
            return customers;
        }

        public string GetFullName()
        {
            return FirstName + " " + LastName + "(" + internalValue + ")";
        }

    }
}

7 个答案:

答案 0 :(得分:14)

在我们的申请中,我们最终使用:

DataContractSerializer xs = new DataContractSerializer(typeof (T));

而不是:

XmlSerializer xs = new XmlSerializer(typeof (T));

解决了这个问题,因为DatacontractSerializer支持Dictionary。

另一种解决方案是XML Serializable Generic Dictionary解决方法也可以在上面的示例中使用,并且在使用它的人的链接上进行了长时间的讨论,可能对处理此问题的人有用。

答案 1 :(得分:9)

这是一个知道如何自行序列化的通用字典类:

  public class XmlDictionary<T, V> : Dictionary<T, V>, IXmlSerializable {
    [XmlType("Entry")]
    public struct Entry {
      public Entry(T key, V value) : this() { Key = key; Value = value; }
      [XmlElement("Key")]
      public T Key { get; set; }
      [XmlElement("Value")]
      public V Value { get; set; }
    }
    System.Xml.Schema.XmlSchema IXmlSerializable.GetSchema() {
      return null;
    }
    void IXmlSerializable.ReadXml(System.Xml.XmlReader reader) {
      this.Clear();
      var serializer = new XmlSerializer(typeof(List<Entry>));
      reader.Read();  // Why is this necessary?
      var list = (List<Entry>)serializer.Deserialize(reader);
      foreach (var entry in list) this.Add(entry.Key, entry.Value);
      reader.ReadEndElement();
    }
    void IXmlSerializable.WriteXml(System.Xml.XmlWriter writer) {
      var list = new List<Entry>(this.Count);
      foreach (var entry in this) list.Add(new Entry(entry.Key, entry.Value));
      XmlSerializer serializer = new XmlSerializer(list.GetType());
      serializer.Serialize(writer, list);
    }
  }

答案 2 :(得分:4)

你不能(自己做不了,这太可怕了); xml序列化程序不会知道如何处理object,因为它不包含有线格式的类型元数据。一个(hacky)选项是将这些all作为字符串流式传输以用于序列化,但是你需要编写许多额外的解析(等)代码。

答案 3 :(得分:1)

您可以改用Binary serialization。 (只需确保所有类都标记为[Serializable]。当然,它不是XML格式,但您没有将其列为要求:)

答案 4 :(得分:0)

我刚发现这个blog post by Rakesh Rajan描述了一种可能的解决方案:

  

通过使类型实现System.Xml.Serialization.IXmlSerializable类来覆盖XmlSerialization。在WriteXml方法中定义如何在XML中序列化对象,并定义如何从ReadXml方法中的xml字符串重新创建对象。

但是这不起作用,因为您的词典包含object而不是特定类型。

答案 5 :(得分:0)

如何将Customer类标记为DataContract,将其属性标记为DataMembers。 DataContract序列化器将为您进行序列化。

答案 6 :(得分:0)

尝试通过BinaryFormatter进行序列化

private void Deserialize()
    {
        try
        {
            var f_fileStream = File.OpenRead(@"dictionarySerialized.xml");
            var f_binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            myDictionary = (Dictionary<string, myClass>)f_binaryFormatter.Deserialize(f_fileStream);
            f_fileStream.Close();
        }
        catch (Exception ex)
        {
            ;
        }
    }
    private void Serialize()
    {
        try
        {
            var f_fileStream = new FileStream(@"dictionarySerialized.xml", FileMode.Create, FileAccess.Write);
            var f_binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            f_binaryFormatter.Serialize(f_fileStream, myDictionary);
            f_fileStream.Close();
        }
        catch (Exception ex)
        {
            ;
        }
    }