如何序列化C#Dictionary<int, string>
?如何序列化字典<int, string>?
0
A
回答
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
類的主要好處是它可以讓你使用任何你想要的字典,你不會陷入特定的實現。
相關問題
- 1. .NET WCF的Json反序列化字典<int, int>
- 2. 序列化字典<int,object>使用JSON.net?
- 3. 執行字典<int,字典<int, int>>,鍵的順序?
- 4. 反序列化一個JSON字典<int,CustomType>到列表<CustomType>
- 5. Newtonsoft -JsonConvert:如何序列化字典中的類對象鍵<class,int>
- 6. 如何將Xml反序列化爲字典<int,string>對象?
- 7. 反序列化字典<string, T>
- 8. 序列化JSON字典<string,string>
- 9. C#反序列化JSON到詞典<INT,元組<string,int>>
- 10. 如何序列化字典<字符串,對象>爲JavaScript?
- 11. 如何返回字典<int, object>?
- 12. 如何從字典<int, string>中提取列表<int>?
- 13. 檢查,如果我的字典<INT,列表<int>>在列表中
- 14. 詞典<struct,int>沒有正確序列化
- 15. JSON.Net如何序列化字典<枚舉,枚舉>?
- 16. 如何反序列化包含字典列表的字典
- 17. 序列化/反序列化字典<字符串,字符串>到XML
- 18. JSON序列化/反序列化爲包含字典的字典
- 19. 如何反序列化嵌套字典?
- 20. 如何序列化字典到base64
- 21. 序列化列表/字典
- 22. 如何正確序列化和反序列化字典的值?
- 23. 使用JSON.NET反序列化和序列化字典<字符串,對象>
- 24. 排序字典<字符串,列表<int>>基於值
- 25. 如何存儲序列化列表<int>在FluentNhibernate
- 26. 如何用javascript製作字典<int, int>
- 27. 轉換IEnumerable的<字典<int, string>>列出<詞典<int, string>>
- 28. 將字典<Int, Object>轉換爲包含lambdas的字典<Int,Object.Property>
- 29. 將字典<int,Enumerable>轉換爲字典<int,Enumerable>反轉內容
- 30. 如何反序列化字典<字符串,字符串[]>在C#?
你能否提供一些關於你想如何序列化的細節? XML?二進制?什麼? – SteinNorheim 2010-04-06 19:42:50
JSON.Net庫也是一個很好的選擇:D – 2010-04-06 20:19:37
如果你想使用JSON,請看這裏:http://www.jarloo.com/serialize-to-json/ – Smolla 2013-01-30 16:57:21