如何在C#中反序列化Xml响应

时间:2019-07-01 10:59:40

标签: c# asp.net-web-api

我有一个可以获取XML响应的API

       public Task<Dictionary<long, string>> GetXMLResponse() 
       {

        Dictionary<long, string> dic = new Dictionary<long, string>();
        dic.Add(1, "a");
        dic.Add(2, "b");

        return dic;
       }

我正在这样从Windows应用程序调用此API

       HttpWebResponse response = (HttpWebResponse)request.GetResponse();

          if (response != null)
                {
               using (var streamReader = new StreamReader(response.GetResponseStream()))
                    {
                       XmlSerializer obj = new XmlSerializer(typeof(List<MyClass>));

                       List<MyClass> class1 = (List<MyClass>)obj.Deserialize(streamReader);

                    }

MyClass就是这样

public class MyClass
{
    [XmlElement(ElementName = "Key")]
    public long Key { get; set; }

    [XmlElement(ElementName = "Value")]
    public string Value { get; set; }
}

我收到关注错误 XML文档(1、2)中有错误。

内部异常是

   <arrayofkeyvalueoflongstring xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays"> was not expected. 

我从API得到的响应

<?xml version="1.0"?>
-<ArrayOfKeyValueOflongstring xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">


-<KeyValueOflongstring>

 <Key>1</Key>

 <Value>a</Value>

</KeyValueOflongstring>


-<KeyValueOflongstring>

 <Key>2</Key>

 <Value>b</Value>

 </KeyValueOflongstring>

 </ArrayOfKeyValueOflongstring>

请为什么我会收到此错误。

预先感谢

0 个答案:

没有答案