我在反序列化从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;
}
}
当我反序列化(传递类型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>
我希望那里有人知道我做错了什么。我一直在反对这个问题太久了,谷歌一直没有帮助我。
答案 0 :(得分: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; }
}
答案 1 :(得分:0)
确保GetResponseStream()
中包含数据。要测试尝试将其保存到文件而不是进行网络连接。将其保存到数据文件并反序列化。如果它被序列化,那就是大部分战斗。如果序列化正确,则反序列化不应该是问题。