簡體   English   中英

C#中的字典數據序列化

[英]Dictionary Data Serialization in C#

我想將字典數據轉換為XML。 我正在嘗試使用XML序列化,但出現錯誤。 下面是我的代碼。

class Program
{

    static void Main(string[] args)
    {
        Dictionary<int, AddressDetails> objDic = new Dictionary<int, AddressDetails>();
        for (int i = 1; i <= 5; i++)
        {
            AddressDetails obj = new AddressDetails();
            obj.HouseNo = i;
            obj.StreetName = "New Street One " + i;
            obj.City = "New Delhi One " + i;
            objDic.Add(i, obj);
        }

        string str = Utility.GetXMLFromObject(objDic);
    }

}

public class AddressDetails 
{
    public int HouseNo { get; set; }
    public string StreetName { get; set; }
    public string City { get; set; }
    private string PoAddress { get; set; }
}

public static class Utility
{
    public static string GetXMLFromObject(object o)
    {
        StringWriter sw = new StringWriter();
        XmlTextWriter tw = null;
        try
        {
            XmlSerializer serializer = new XmlSerializer(o.GetType());
            tw = new XmlTextWriter(sw);
            serializer.Serialize(tw, o);
        }
        catch (Exception ex)
        {
            //Handle Exception Code
        }
        finally
        {
            sw.Close();
            if (tw != null)
            {
                tw.Close();
            }
        }
        return sw.ToString();
    }
}

錯誤代碼行: XmlSerializer serializer = new XmlSerializer(o.GetType());

錯誤說明:

類型System.Collections.Generic.Dictionary`2 [[System.Int32,mscorlib,Version = 4.0.0.0,Culture = neutral,PublicKeyToken = b77a5c561934e089],[ConsoleApplication5.AddressDetails,ConsoleApplication5,Version = 1.0.0.0,Culture = neutral ,PublicKeyToken = null]]不支持,因為它實現了IDictionary。

請提出建議。

嘗試以下鏈接中說明的解決方案:

http://theburningmonk.com/2010/05/net-tips-xml-serialize-or-deserialize-dictionary-in-csharp/

您必須使用DataContract序列化而不是XmlSerialization或使用自定義詞典類型。

使用以下字典擴展名。

[XmlRoot("Dictionary")]
public class DictionaryEx<TKey, TValue> : Dictionary<TKey, TValue>, IXmlSerializable
{
    public XmlSchema GetSchema()
    {
        return null;
    }

    public void ReadXml(XmlReader reader)
    {
        XDocument document = null;
        using (XmlReader subtreeReader = reader.ReadSubtree())
        {
            document = XDocument.Load(subtreeReader);
        }

        if (document == null)
            return;

        XmlSerializer serializer = new XmlSerializer(typeof(KeyValuePairEx<TKey, TValue>));
        foreach (XElement element in document.Descendants(XName.Get("Item")))
        {
            using (XmlReader xmlReader = element.CreateReader())
            {
                var pair = serializer.Deserialize(xmlReader) as KeyValuePairEx<TKey, TValue>;
                this.Add(pair.Key, pair.Value);
            }
        }

        reader.ReadEndElement();
    }

    public void WriteXml(XmlWriter writer)
    {
        XmlSerializer serializer = new XmlSerializer(typeof(KeyValuePairEx<TKey, TValue>));
        XmlSerializerNamespaces xmlNameSpaces = new XmlSerializerNamespaces();
        xmlNameSpaces.Add(string.Empty, string.Empty);

        foreach (TKey key in this.Keys)
        {
            TValue value = this[key];
            var pair = new KeyValuePairEx<TKey, TValue>(key, value);
            serializer.Serialize(writer, pair, xmlNameSpaces);
        }
    }

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

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

        public KeyValuePairEx()
        {
        }

        public KeyValuePairEx(TKey key, TValue value)
        {
            Key = key;
            Value = value;
        }
    }
}

上面的代碼來自Keyo

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM