2010-04-06 29 views
0

如何序列化C#Dictionary<int, string>如何序列化字典<int, string>?

+4

你能否提供一些關於你想如何序列化的細節? XML?二進制?什麼? – SteinNorheim 2010-04-06 19:42:50

+0

JSON.Net庫也是一個很好的選擇:D – 2010-04-06 20:19:37

+0

如果你想使用JSON,請看這裏:http://www.jarloo.com/serialize-to-json/ – Smolla 2013-01-30 16:57:21

回答

4

下面是一個簡單的演示:

var lookup = new Dictionary<int, string>(); 

lookup.Add(1, "123"); 
lookup.Add(2, "456"); 

using (var ms = new MemoryStream()) 
{ 
    var formatter = 
     new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); 

    formatter.Serialize(ms, lookup); 
    lookup = null; 

    ms.Position = 0; 
    lookup = (Dictionary<int, string>) formatter.Deserialize(ms); 
} 

foreach(var i in lookup.Keys) 
{ 
    Console.WriteLine("{0}: {1}", i, lookup[i]); 
} 

但你可能有更具體。

0

你可以編寫自己的對象,它有以下兩種方法,Serialize和DeSerialize。的Form_Load用於測試

public partial class Form1 : Form 
{ 
    public Form1() 
    { 
     InitializeComponent(); 
    } 

    private void Form1_Load(object sender, EventArgs e) 
    { 
     Dictionary<int, string> list = new Dictionary<int, string>(); 

     list.Add(1, "one"); 
     list.Add(2, "two"); 
     list.Add(3, "three"); 

     Dictionary<int, string> list2 = Deserialize(Serialize(list)); 

    } 

    public string Serialize(Dictionary<int, string> classObject) 
    { 
     StringBuilder output = new StringBuilder(); 

     output.Append("<DictionaryIntString>"); 

     foreach (int key in classObject.Keys) 
     { 
      output.Append(String.Format("<Key value=\"{0}\">",key)); 
      output.Append(String.Format("<Value>{0}</Value></Key>", classObject[key])); 

     } 
     output.Append("</DictionaryIntString>"); 
     return output.ToString(); 


    } 

    public Dictionary<int, string> Deserialize(string input) 
    { 
     Dictionary<int, string> output = new Dictionary<int, string>(); 

     XmlDocument xml = new XmlDocument(); 
     xml.LoadXml(input); 

     foreach (XmlNode node in xml.GetElementsByTagName("Key")) 
     { 
      output.Add(Int32.Parse(node.Attributes["value"].InnerText),node.FirstChild.InnerText); 

     } 

     return output; 
    } 
} 
1

假設你正在談論XML序列化,你可以使用保羅韋爾特的SerializableDictionary類,由凱文的建議,但這裏的另一種解決方案,不涉及IXmlSerializable自定義實現。

我的想法是,字典可以看作是鍵值對的集合。 XmlSerializer可以序列化一個集合,並且它可以序列化一個鍵值對。所以你只需要爲字典創建一個包裝,這看起來像一個集合,以便XmlSerializer可以處理它而不抱怨。

這裏是我的實現:

一個XmlDictionaryEntry類來保存鍵值對

public class XmlDictionaryEntry<TKey, TValue> 
{ 
    public TKey Key { get; set; } 
    public TValue Value { get; set; } 
} 

一個XmlDictionaryEntryCollection(該KeyValuePair<TKey, TValue>類不能使用,因爲它的屬性是隻讀的序列化到XML)類,實現鍵值對的集合並使用字典來存儲它們

public class XmlDictionaryEntryCollection<TKey, TValue> : ICollection<XmlDictionaryEntry<TKey, TValue>> 
{ 
    public XmlDictionaryEntryCollection() 
    { 
     this.Dictionary = new Dictionary<TKey, TValue>(); 
    } 

    public XmlDictionaryEntryCollection(IDictionary<TKey, TValue> dictionary) 
    { 
     dictionary.CheckArgumentNull("dictionary"); 
     this.Dictionary = dictionary; 
    } 

    [XmlIgnore] 
    public IDictionary<TKey, TValue> Dictionary { get; private set; } 

    #region ICollection<XmlDictionaryEntry<TKey,TValue>> Members 

    public void Add(XmlDictionaryEntry<TKey, TValue> item) 
    { 
     this.Dictionary.Add(item.Key, item.Value); 
    } 

    public void Clear() 
    { 
     this.Dictionary.Clear(); 
    } 

    public bool Contains(XmlDictionaryEntry<TKey, TValue> item) 
    { 
     return this.Dictionary.ContainsKey(item.Key); 
    } 

    public void CopyTo(XmlDictionaryEntry<TKey, TValue>[] array, int arrayIndex) 
    { 
     int index = arrayIndex; 
     if (arrayIndex + this.Dictionary.Count > array.Length) 
      throw new ArgumentException(ExceptionMessages.CopyToNotEnoughSpace); 

     foreach (var kvp in this.Dictionary) 
     { 
      var entry = new XmlDictionaryEntry<TKey, TValue> 
      { 
       Key = kvp.Key, 
       Value = kvp.Value 
      }; 
      array[index++] = entry; 
     } 
    } 

    public int Count 
    { 
     get { return this.Dictionary.Count; } 
    } 

    public bool IsReadOnly 
    { 
     get { return this.Dictionary.IsReadOnly; } 
    } 

    public bool Remove(XmlDictionaryEntry<TKey, TValue> item) 
    { 
     return this.Dictionary.Remove(item.Key); 
    } 

    #endregion 

    #region IEnumerable<XmlDictionaryEntry<TKey,TValue>> Members 

    public IEnumerator<XmlDictionaryEntry<TKey, TValue>> GetEnumerator() 
    { 
     foreach (var kvp in this.Dictionary) 
     { 
      yield return new XmlDictionaryEntry<TKey, TValue> 
      { 
       Key = kvp.Key, 
       Value = kvp.Value 
      }; 
     } 
    } 

    #endregion 

    #region IEnumerable Members 

    IEnumerator IEnumerable.GetEnumerator() 
    { 
     return this.GetEnumerator(); 
    } 

    #endregion 
} 

A N分機方法,使其更容易地創建(利用通用的類型推斷的)包裝:

public static class XmlSerializationExtension() 
{ 
    public static XmlDictionaryEntryCollection<TKey, TValue> AsXmlSerializable<TKey, TValue>(this IDictionary<TKey, TValue> dictionary) 
    { 
     if (dictionary != null) 
      return new XmlDictionaryEntryCollection<TKey, TValue>(dictionary); 
     else 
      return null; 
    } 
} 

這裏是你如何使用它:

假設你有這樣的特性:

public Dictionary<string, Foo> Foos { get; set; } 

您只需要將該屬性從序列化程序中隱藏(使用XmlIgnore屬性),並將XmlDictionaryEntryCollection序列化爲:

[XmlIgnore] 
public Dictionary<string, Foo> Foos { get; set; } 

[XmlElement("Foos")] 
public XmlDictionaryEntryCollection SerializableFoos 
{ 
    get { return Foos.AsXmlSerializable(); } 
    set { Foos = value.Dictionary; } 
} 

這種技術比SerializableDictionary類的主要好處是它可以讓你使用任何你想要的字典,你不會陷入特定的實現。

相關問題