How can I serialize an object with a Dictionary property?

前端 未结 7 543
故里飘歌
故里飘歌 2021-01-04 08:04

In the example code below, I get this error:

Element TestSerializeDictionary123.Customer.CustomProperties vom Typ System.Collec

7条回答
  •  北荒
    北荒 (楼主)
    2021-01-04 08:55

    Here's a generic dictionary class that knows how to serialize itself:

      public class XmlDictionary : Dictionary, 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));
          reader.Read();  // Why is this necessary?
          var list = (List)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(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);
        }
      }
    

提交回复
热议问题