无法使用 WCF Web 服务的 XMLSerializer 结果进行反序列化
这是尝试从紧凑框架获取 http 服务的代码。
List<Table> tables;
using (Stream r = response.GetResponseStream())
{
XmlSerializer serializer = new XmlSerializer(typeof(Table),"http://schemas.datacontract.org/2004/07/");
tables=(List<Table>) serializer.Deserialize(r);
}
response.Close();
它失败并显示 {"XML 文档 (1, 2) 中存在错误。"}
{"<ArrayOfTable xmlns='http://schemas.datacontract.org/2004/07/WpfApplication1.Data.Model'> was not expected."}
表命名空间是相同的... 我不知道那里出了什么问题...
更新
问题是我有 typeof(Table) 而不是 typeof(List) ,它部分工作..没有错误,但创建的表值为空!
Here is the code trying from compact framework to get http service..
List<Table> tables;
using (Stream r = response.GetResponseStream())
{
XmlSerializer serializer = new XmlSerializer(typeof(Table),"http://schemas.datacontract.org/2004/07/");
tables=(List<Table>) serializer.Deserialize(r);
}
response.Close();
It fails with {"There is an error in XML document (1, 2)."}
{"<ArrayOfTable xmlns='http://schemas.datacontract.org/2004/07/WpfApplication1.Data.Model'> was not expected."}
Table namespace is the same...
I dont know whats wrong there...
UPDATE
Problem was that i had typeof(Table) not typeof(List<Table>
) which works partially.. No error but created tables values are null!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
XmlSerializer 构造函数的第二个参数适用于序列化和反序列化。因此,第二个参数(命名空间)应该与收到的参数相同。因此,您最终会得到:
请注意命名空间字符串末尾的“WpfApplication1.Data.Model”。
摆脱命名空间问题的一种方法。是在您的模型类(表)上指定它不应使用名称空间:
这样您就不需要为反序列化指定名称空间。
希望有帮助!
The second parameter on the XmlSerializer constructor works for both serializing and deserializing. So, on the second parameter (the namespace) should be the same to the one being received. So you'll end up having:
Note the "WpfApplication1.Data.Model" at the end of the namespace string.
One way to get rid of the namespace thing. Is to specify on your model class (Table) that it should not use a namespace:
That way you don't need to specify the namespace for deserialization.
Hope it helps!
不确定这是否有帮助,但我们遇到了类似的问题。我们发现,如果我们的 WCF 服务使用 XmlSerializerFormat,我们可以轻松地反序列化我们的对象,而不是使用 DataContract/DataMember 属性装饰数千个数据元素并使用(默认)DataContractSerializer。
这就是我们反序列化对象的方式:
Not sure if this will help, but we had a similar issue. Instead of decorating thousands of data elements with DataContract/DataMember attributes and using the (default) DataContractSerializer, we found that if our WCF service used the XmlSerializerFormat instead, we could easily deserialize our objects.
This is how we're deserializing the objects:
返回具有单个 List 属性的对象,而不是返回 List。
Instead of returning a List return an object that has a single property of List.