C#KeyValuePair将列表反序列化为“值”字段

时间:2016-12-27 13:39:10

标签: c# .net c#-4.0

我有一个用XML序列化的KeyValuePair对象,对于每个键,都有一个像这样的值列表:

<WritableKeyValuePairOfKeyContraenteArrayOfAddress>
   <key>
      <KeyContaente>123456</KeyContaente>
   </key>
   <value>
      <Address>Maple road 12</Address>
   </value>
   <value>
      <Address>Oak street 71</Address>
   </value>
</WritableKeyValuePairOfKeyContraenteArrayOfAddress>

问题是:当我反序列化时,对象的值只包含一个元素:第一个(“Maple road 12”)。为什么会这样?

编辑: 的序列化

public static string Serializza<T>(T objectToSerialize)
    {
        using (MemoryStream memStm = new MemoryStream())
        {
            var serializer = new DataContractSerializer(typeof(T));
            serializer.WriteObject(memStm, objectToSerialize);

            memStm.Seek(0, SeekOrigin.Begin);

            using (var streamReader = new StreamReader(memStm))
            {
                string result = streamReader.ReadToEnd();
                return result;
            }
        }
    }

反序列化

    private static T Deserializza<T>(string xmlString)
    {
        if (xmlString.Length > 0)
        {
            try
            {
                var serializer = new DataContractSerializer(typeof(T));
                using (System.IO.MemoryStream memStm = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(xmlString)))
                {
                    return (T)serializer.ReadObject(memStm);
                }
            }
            catch
            {
                return default(T);
            }
        }
        else
            return default(T);
    }

KeyValuePair就像一个词典:

[Serializable, StructLayout(LayoutKind.Sequential)]
public class WritableKeyValuePair<TKey, TValue> : IWritableKeyValuePair
{
    private TKey key;
    private TValue value;

    public WritableKeyValuePair() { }
    public WritableKeyValuePair(TKey key, TValue value)
    {
        this.key = key;
        this.value = value;
    }

    public override string ToString()
    {
        return WKVPUtils<TKey, TValue>.ToString(key, value);
    }

    ////[XmlProcessDeep()]
    public TValue Value
    {
        get { return this.value; }
        set { this.value = value; }
    }

    public TKey Key
    {
        get { return this.key; }
        set { this.key = value; }
    }

    internal static class WKVPUtils<TKey, TValue>
    {
        public static string ToString(TKey Key, TValue Value)
        {
            StringBuilder builder1 = new StringBuilder();
            builder1.Append('[');
            if (Key != null)
                builder1.Append(Key.ToString());
            builder1.Append(", ");
            if (Value != null)
                builder1.Append(Value.ToString());
            builder1.Append(']');
            return builder1.ToString();
        }
    }
}

2 个答案:

答案 0 :(得分:1)

(代表OP发布)

这已经解决了。我必须按如下方式编辑XML结构:

public static Date getDateFromIsoISO8601(String str) {
        try {
            return ISO8601Utils.parse(str, new ParsePosition(0));
        } catch (Exception e) {
            Log.e("Parsing","error:getDateFromIsoISO8601: " + e.getMessage());
            return null;
        }
    }

在我为每个<WritableKeyValuePairOfKeyContraenteArrayOfAddress> <key> <KeyContaente>123456</KeyContaente> </key> <value> <Address>Maple road 12</Address> <Address>Oak street 71</Address> </value> </WritableKeyValuePairOfKeyContraenteArrayOfAddress> 标记添加<value>标记之前,现在只有一个打开和关闭<Address>标记,其中包含多个<value>标记。

答案 1 :(得分:0)

试试这个

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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string xml =
                "<Root>" +
                "<WritableKeyValuePairOfKeyContraenteArrayOfAddress>" +
                   "<key>" +
                      "<KeyContaente>123456</KeyContaente>" +
                   "</key>" +
                   "<value>" +
                      "<Address>Maple road 12</Address>" +
                      "<Address>Oak street 71</Address>" +
                   "</value>" +
                "</WritableKeyValuePairOfKeyContraenteArrayOfAddress>" +
                "</Root>";

            XElement elements = XElement.Parse(xml);

            Dictionary<string, List<string>> dict = elements.Descendants("WritableKeyValuePairOfKeyContraenteArrayOfAddress").Select(x => new
            {
                key = (string)x.Descendants("KeyContaente").FirstOrDefault(),
                values = x.Descendants("Address").Select(y => (string)y).ToList()
            }).GroupBy(x => x.key, y => y.values)
            .ToDictionary(x => x.Key, y => y.FirstOrDefault());
        }
    }
}