2

我在反序列化从 Web 服务收到的 XML 响应时遇到问题。响应如下所示:

<CreateSubscribersResultCollection xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
    <CreatedSubscriberIds xmlns:a="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
        <a:long>206464306</a:long>
        <a:long>306664316</a:long>
    </CreatedSubscriberIds>
    <FailedCreatedSubscribers xmlns:a="http://schemas.microsoft.com/2003/10/Serialization/Arrays" />
</CreateSubscribersResultCollection>

我用来反序列化 XML 的代码如下所示:

internal T GetQueuedResults<T>(string url)
{
    WebRequest request = GetRequestObject(url, "GET");
    var httpResponse = (HttpWebResponse)request.GetResponse();

    using (var responseStream = httpResponse.GetResponseStream())
    {
        XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
        var response = (T)xmlSerializer.Deserialize(responseStream);

        return response;
    }
}

当我反序列化(传递 type CreateSubscribersResultCollection)时,我根本没有收到任何错误,而是CreatedSubscriberIds长度为0. 我很确定错误在于我设计CreateSubscribersResultCollection课程的方式,但我无法弄清楚错误可能是什么。该类如下所示:

[DataContract]
public class CreateSubscribersResultCollection : RequestBase
{
    [XmlArray("CreatedSubscriberIds")]
    [XmlArrayItem(typeof(long))]
    public List<long> CreatedSubscriberIds { get; set; }

    [XmlElement("FailedCreatedSubscribers")]
    public string FailedCreatedSubscribers { get; set; }
}

当我实例化该类并对其进行序列化时,出于调试目的,我得到以下结果:

<CreateSubscribersResultCollection xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <CreatedSubscriberIds>
        <long>206464306</long>
        <long>306664316</long>
    </CreatedSubscriberIds>
    <FailedCreatedSubscribers />
</CreateSubscribersResultCollection>

我希望有人知道我做错了什么。我一直在努力反对这个问题太久了,谷歌对我没有帮助。

4

2 回答 2

2

尝试像这样指定命名空间:

    [DataContract]
public class CreateSubscribersResultCollection : RequestBase
{
    [XmlArray("CreatedSubscriberIds")]
    [XmlArrayItem(typeof(long), Namespace="http://schemas.microsoft.com/2003/10/Serialization/Arrays")]
    public List<long> CreatedSubscriberIds { get; set; }

    [XmlElement("FailedCreatedSubscribers")]
    public string FailedCreatedSubscribers { get; set; }
}
于 2012-05-15T07:45:56.840 回答
0

确保GetResponseStream()其中有数据。要测试尝试将其保存到文件中,而不是进行网络连接。将其保存到数据文件并反序列化。如果它正在被连载,那是大部分的战斗。如果正确序列化,反序列化应该不是问题。

于 2012-05-15T07:46:55.823 回答