序列化包含Dictionary成员的类


144

扩展之前的问题,我决定对配置文件类进行反序列化,该类非常有用。

我现在想存储的驱动器号关联数组映射(关键是驱动器盘符,价值是网络路径)和使用都试过DictionaryHybridDictionaryHashtable这个,但是打电话时,我总是得到下面的错误ConfigFile.Load()或者ConfigFile.Save()

反映类型'App.ConfigFile'的错误。[snip] System.NotSupportedException:无法序列化成员App.Configfile.mappedDrives [snip]

从我看过的书中可以将Dictionary和HashTables序列化,那么我在做什么错呢?

[XmlRoot(ElementName="Config")]
public class ConfigFile
{
    public String guiPath { get; set; }
    public string configPath { get; set; }
    public Dictionary<string, string> mappedDrives = new Dictionary<string, string>();

    public Boolean Save(String filename)
    {
        using(var filestream = File.Open(filename, FileMode.OpenOrCreate,FileAccess.ReadWrite))
        {
            try
            {
                var serializer = new XmlSerializer(typeof(ConfigFile));
                serializer.Serialize(filestream, this);
                return true;
            } catch(Exception e) {
                MessageBox.Show(e.Message);
                return false;
            }
        }
    }

    public void addDrive(string drvLetter, string path)
    {
        this.mappedDrives.Add(drvLetter, path);
    }

    public static ConfigFile Load(string filename)
    {
        using (var filestream = File.Open(filename, FileMode.Open, FileAccess.Read))
        {
            try
            {
                var serializer = new XmlSerializer(typeof(ConfigFile));
                return (ConfigFile)serializer.Deserialize(filestream);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + ex.ToString());
                return new ConfigFile();
            }
        }
    }
}

Answers:


77

您不能序列化实现IDictionary的类。查看此链接

问:为什么我不能序列化哈希表?

答:XmlSerializer无法处理实现IDictionary接口的类。这部分是由于调度约束,部分是由于哈希表在XSD类型系统中没有对应项。唯一的解决方案是实现不实现IDictionary接口的自定义哈希表。

因此,我认为您需要为此创建自己的词典版本。检查另一个问题


4
只是想知道DataContractSerializer班级能做到这一点。只是输出有点难看。
退役

186

Paul Welter的Weblog上有一个解决方案-XML可序列化通用字典

由于某些原因,.net 2.0中的通用词典无法XML序列化。以下代码段是xml可序列化的通用字典。通过实现IXmlSerializable接口,可以对字典进行序列化。

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

[XmlRoot("dictionary")]
public class SerializableDictionary<TKey, TValue>
    : Dictionary<TKey, TValue>, IXmlSerializable
{
    public SerializableDictionary() { }
    public SerializableDictionary(IDictionary<TKey, TValue> dictionary) : base(dictionary) { }
    public SerializableDictionary(IDictionary<TKey, TValue> dictionary, IEqualityComparer<TKey> comparer) : base(dictionary, comparer) { }
    public SerializableDictionary(IEqualityComparer<TKey> comparer) : base(comparer) { }
    public SerializableDictionary(int capacity) : base(capacity) { }
    public SerializableDictionary(int capacity, IEqualityComparer<TKey> comparer) : base(capacity, comparer) { }

    #region IXmlSerializable Members
    public System.Xml.Schema.XmlSchema GetSchema()
    {
        return null;
    }

    public void ReadXml(System.Xml.XmlReader reader)
    {
        XmlSerializer keySerializer = new XmlSerializer(typeof(TKey));
        XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue));

        bool wasEmpty = reader.IsEmptyElement;
        reader.Read();

        if (wasEmpty)
            return;

        while (reader.NodeType != System.Xml.XmlNodeType.EndElement)
        {
            reader.ReadStartElement("item");

            reader.ReadStartElement("key");
            TKey key = (TKey)keySerializer.Deserialize(reader);
            reader.ReadEndElement();

            reader.ReadStartElement("value");
            TValue value = (TValue)valueSerializer.Deserialize(reader);
            reader.ReadEndElement();

            this.Add(key, value);

            reader.ReadEndElement();
            reader.MoveToContent();
        }
        reader.ReadEndElement();
    }

    public void WriteXml(System.Xml.XmlWriter writer)
    {
        XmlSerializer keySerializer = new XmlSerializer(typeof(TKey));
        XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue));

        foreach (TKey key in this.Keys)
        {
            writer.WriteStartElement("item");

            writer.WriteStartElement("key");
            keySerializer.Serialize(writer, key);
            writer.WriteEndElement();

            writer.WriteStartElement("value");
            TValue value = this[key];
            valueSerializer.Serialize(writer, value);
            writer.WriteEndElement();

            writer.WriteEndElement();
        }
    }
    #endregion
}

16
+1。嘿,为什么Stack Overflow没有复制代码按钮?嗯?因为此代码值得复制!
toddmo

1
+1很棒的答案。也适用于SortedList,只需将“ SerializableDictionary”更改为“ SerializableSortedList”,将“ Dictionary <TKey,TValue>”更改为“ SortedList <TKey,TValue>”。
kdmurray 2014年

1
+1和一个建议。当SerializableDictionary对象包含多个元素时,将引发异常。ReadXml()和WriteXml()应该修改为移动ReadStartElement(“ item”);。和WriteStartElement(“ item”); 及其关联的ReadEndElement()和WriteEndElement()退出while循环。
MNS 2015年

1
这是否意味着在以后的框架中IDictionary可序列化?
托马斯

1
如果字典正在存储string值,该实现将起作用,但是InvalidOperationException如果您尝试在其中存储自定义对象或字符串数​​组,则会在反序列化时引发意外的包装元素。(有关此问题的示例,请参阅我的问题。)
Christopher Kyle Horton

57

除了使用之外,XmlSerializer您还可以使用System.Runtime.Serialization.DataContractSerializer。这可以序列化字典,并且不费吹灰之力。

这是完整示例的链接,http://theburningmonk.com/2010/05/net-tips-xml-serialize-or-deserialize-dictionary-in-csharp/


2
最好的答案,放手。
DWRoelands

同意,这是最佳答案。干净,简单且干燥(不要重复自己)。
Nolonar

与DataContractSerializer的问题是,它系列化和按字母顺序反序列化,所以如果你试图反序列化的东西在错误的顺序,将在你的对象空的属性,静默失败
superjugy

14

创建序列化代理。

例如,您有一个类别为Dictionary的公共属性。

为了支持这种类型的Xml序列化,请创建一个通用键值类:

public class SerializeableKeyValue<T1,T2>
{
    public T1 Key { get; set; }
    public T2 Value { get; set; }
}

将XmlIgnore属性添加到原始属性:

    [XmlIgnore]
    public Dictionary<int, string> SearchCategories { get; set; }

公开一个数组类型的公共属性,该属性包含一个SerializableKeyValue实例数组,这些实例用于序列化和反序列化为SearchCategories属性:

    public SerializeableKeyValue<int, string>[] SearchCategoriesSerializable
    {
        get
        {
            var list = new List<SerializeableKeyValue<int, string>>();
            if (SearchCategories != null)
            {
                list.AddRange(SearchCategories.Keys.Select(key => new SerializeableKeyValue<int, string>() {Key = key, Value = SearchCategories[key]}));
            }
            return list.ToArray();
        }
        set
        {
            SearchCategories = new Dictionary<int, string>();
            foreach (var item in value)
            {
                SearchCategories.Add( item.Key, item.Value );
            }
        }
    }

我喜欢它,因为它使序列化与字典成员分离。如果我有一个经常使用的类想要向其中添加序列化功能,那么包装字典可能会导致继承类型的中断。
VoteCoffee 2014年

对于实现此目的的任何人要当心:如果您尝试将代理属性设置为List(或任何其他集合),那么XML序列化程序将不会调用setter(而是调用getter并尝试将其添加到返回的列表中,这显然不是您想要的)。坚持此模式的数组。
Fraxtil

9

您应该探索Json.Net,它非常易于使用,并允许直接在Dictionary中反序列化Json对象。

james_newtonking

例:

string json = @"{""key1"":""value1"",""key2"":""value2""}";
Dictionary<string, string> values = JsonConvert.DeserializeObject<Dictionary<string, string>>(json); 
Console.WriteLine(values.Count);
// 2
Console.WriteLine(values["key1"]);
// value1

6

字典和哈希表无法使用序列化XmlSerializer。因此,您不能直接使用它们。解决方法是使用XmlIgnore属性对序列化程序隐藏那些属性,并通过可序列化的键值对列表公开它们。

PS:构造一个XmlSerializer非常昂贵,因此,如果有可能重新使用它,请务必对其进行缓存。


4

我想要一个使用xml属性作为键/值的SerializableDictionary类,所以我改编了Paul Welter的类。

这将产生如下的xml:

<Dictionary>
  <Item Key="Grass" Value="Green" />
  <Item Key="Snow" Value="White" />
  <Item Key="Sky" Value="Blue" />
</Dictionary>"

码:

using System.Collections.Generic;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Serialization;

namespace DataTypes {
    [XmlRoot("Dictionary")]
    public class SerializableDictionary<TKey, TValue>
        : Dictionary<TKey, TValue>, IXmlSerializable {
        #region IXmlSerializable Members
        public System.Xml.Schema.XmlSchema GetSchema() {
            return null;
        }

        public void ReadXml(XmlReader reader) {
            XDocument doc = null;
            using (XmlReader subtreeReader = reader.ReadSubtree()) {
                doc = XDocument.Load(subtreeReader);
            }
            XmlSerializer serializer = new XmlSerializer(typeof(SerializableKeyValuePair<TKey, TValue>));
            foreach (XElement item in doc.Descendants(XName.Get("Item"))) {
                using(XmlReader itemReader =  item.CreateReader()) {
                    var kvp = serializer.Deserialize(itemReader) as SerializableKeyValuePair<TKey, TValue>;
                    this.Add(kvp.Key, kvp.Value);
                }
            }
            reader.ReadEndElement();
        }

        public void WriteXml(System.Xml.XmlWriter writer) {
            XmlSerializer serializer = new XmlSerializer(typeof(SerializableKeyValuePair<TKey, TValue>));
            XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
            ns.Add("", "");
            foreach (TKey key in this.Keys) {
                TValue value = this[key];
                var kvp = new SerializableKeyValuePair<TKey, TValue>(key, value);
                serializer.Serialize(writer, kvp, ns);
            }
        }
        #endregion

        [XmlRoot("Item")]
        public class SerializableKeyValuePair<TKey, TValue> {
            [XmlAttribute("Key")]
            public TKey Key;

            [XmlAttribute("Value")]
            public TValue Value;

            /// <summary>
            /// Default constructor
            /// </summary>
            public SerializableKeyValuePair() { }
        public SerializableKeyValuePair (TKey key, TValue value) {
            Key = key;
            Value = value;
        }
    }
}
}

单元测试:

using System.IO;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace DataTypes {
    [TestClass]
    public class SerializableDictionaryTests {
        [TestMethod]
        public void TestStringStringDict() {
            var dict = new SerializableDictionary<string, string>();
            dict.Add("Grass", "Green");
            dict.Add("Snow", "White");
            dict.Add("Sky", "Blue");
            dict.Add("Tomato", "Red");
            dict.Add("Coal", "Black");
            dict.Add("Mud", "Brown");

            var serializer = new System.Xml.Serialization.XmlSerializer(dict.GetType());
            using (var stream = new MemoryStream()) {
                // Load memory stream with this objects xml representation
                XmlWriter xmlWriter = null;
                try {
                    xmlWriter = XmlWriter.Create(stream);
                    serializer.Serialize(xmlWriter, dict);
                } finally {
                    xmlWriter.Close();
                }

                // Rewind
                stream.Seek(0, SeekOrigin.Begin);

                XDocument doc = XDocument.Load(stream);
                Assert.AreEqual("Dictionary", doc.Root.Name);
                Assert.AreEqual(dict.Count, doc.Root.Descendants().Count());

                // Rewind
                stream.Seek(0, SeekOrigin.Begin);
                var outDict = serializer.Deserialize(stream) as SerializableDictionary<string, string>;
                Assert.AreEqual(dict["Grass"], outDict["Grass"]);
                Assert.AreEqual(dict["Snow"], outDict["Snow"]);
                Assert.AreEqual(dict["Sky"], outDict["Sky"]);
            }
        }

        [TestMethod]
        public void TestIntIntDict() {
            var dict = new SerializableDictionary<int, int>();
            dict.Add(4, 7);
            dict.Add(5, 9);
            dict.Add(7, 8);

            var serializer = new System.Xml.Serialization.XmlSerializer(dict.GetType());
            using (var stream = new MemoryStream()) {
                // Load memory stream with this objects xml representation
                XmlWriter xmlWriter = null;
                try {
                    xmlWriter = XmlWriter.Create(stream);
                    serializer.Serialize(xmlWriter, dict);
                } finally {
                    xmlWriter.Close();
                }

                // Rewind
                stream.Seek(0, SeekOrigin.Begin);

                XDocument doc = XDocument.Load(stream);
                Assert.AreEqual("Dictionary", doc.Root.Name);
                Assert.AreEqual(3, doc.Root.Descendants().Count());

                // Rewind
                stream.Seek(0, SeekOrigin.Begin);
                var outDict = serializer.Deserialize(stream) as SerializableDictionary<int, int>;
                Assert.AreEqual(dict[4], outDict[4]);
                Assert.AreEqual(dict[5], outDict[5]);
                Assert.AreEqual(dict[7], outDict[7]);
            }
        }
    }
}

1
看起来不错,但由于字典空而失败。您需要ReadXML方法中的reader.IsEmptyElement测试。
AnthonyVO

2

Dictionary类实现ISerializable。类字典的定义如下。

[DebuggerTypeProxy(typeof(Mscorlib_DictionaryDebugView<,>))]
[DebuggerDisplay("Count = {Count}")]
[Serializable]
[System.Runtime.InteropServices.ComVisible(false)]
public class Dictionary<TKey,TValue>: IDictionary<TKey,TValue>, IDictionary, IReadOnlyDictionary<TKey, TValue>, ISerializable, IDeserializationCallback  

我不认为这是问题。请参考下面的链接,该链接表示如果您具有其他不可序列化的数据类型,则词典将不会被序列化。 http://forums.asp.net/t/1734187.aspx?是+字典+序列化+


在最新版本中确实如此,但是在.NET 2中,即使在今天,Dictionary也无法序列化。我今天才通过针对.NET 3.5的项目确认了这一点,这就是我找到此线程的方式。
Bruce

2

您可以使用ExtendedXmlSerializer。如果您上课:

public class ConfigFile
{
    public String guiPath { get; set; }
    public string configPath { get; set; }
    public Dictionary<string, string> mappedDrives {get;set;} 

    public ConfigFile()
    {
        mappedDrives = new Dictionary<string, string>();
    }
}

并创建此类的实例:

ConfigFile config = new ConfigFile();
config.guiPath = "guiPath";
config.configPath = "configPath";
config.mappedDrives.Add("Mouse", "Logitech MX Master");
config.mappedDrives.Add("keyboard", "Microsoft Natural Ergonomic Keyboard 4000");

您可以使用ExtendedXmlSerializer序列化此对象:

ExtendedXmlSerializer serializer = new ExtendedXmlSerializer();
var xml = serializer.Serialize(config);

输出xml将如下所示:

<?xml version="1.0" encoding="utf-8"?>
<ConfigFile type="Program+ConfigFile">
    <guiPath>guiPath</guiPath>
    <configPath>configPath</configPath>
    <mappedDrives>
        <Item>
            <Key>Mouse</Key>
            <Value>Logitech MX Master</Value>
        </Item>
        <Item>
            <Key>keyboard</Key>
            <Value>Microsoft Natural Ergonomic Keyboard 4000</Value>
        </Item>
    </mappedDrives>
</ConfigFile>

您可以从nuget安装ExtendedXmlSerializer 或运行以下命令:

Install-Package ExtendedXmlSerializer

这是在线示例


By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.