使用 RestSharp 发布数据时序列化对象
我最近开始使用 RestSharp 来使用使用 XML 的 REST 服务。
它使得将 XML 对象反序列化为自定义对象集合变得非常简单。但我的问题是,在回发到服务时重新序列化的最佳方法是什么?
我应该使用 LINQ-to-XML 重新序列化吗?我尝试使用 Serializeable
属性和 SerializeToXml
实用程序函数,但是当我这样做时,它似乎破坏了 RestSharp 执行的反序列化。
I've recently started using RestSharp to consume a REST service which uses XML.
It makes deserializing objects from XML to a collection of custom objects trivial. But my question is what is the best way to reserialize when posting back to the service?
Should I use LINQ-to-XML to reserialize? I tried using the Serializeable
attribute and a SerializeToXml
utility function, but when I do so it seems to break the deserializing performed by RestSharp.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我已经能够使用属性来获取我需要的所有内容,尽管我的情况比较简单。例如,为了让它反序列化带有破折号的节点,然后能够序列化到相同的节点名称,我使用了以下命令:
因此,在您的示例中,序列化不尊重
[XmlElement("elementName" )]
。相反,您需要使用[SerializeAs(Name = "elementName")]
。我通过浏览 RestSharp 项目中的测试代码发现了这一点。
I have been able to use attributes to get all of what I need, although my situation is relatively simple. For example, to get it to deserialize nodes with dashes in them, and then to be able to serialize to the same node name I used this:
So, in your example, serialization doesn't respect
[XmlElement("elementName")]
. Instead, you will need to use[SerializeAs(Name = "elementName")]
.I found this by trolling through the test code in the RestSharp project.
查看 RestSharp 的源代码后,我发现他们实际上有一个名为
DotNetXmlSerializer
的System.Xml.Serialization.XmlSerializer
内置包装器,只是默认情况下不使用它。要使用它,只需添加以下行:After looking at the source code for RestSharp I found that they actually have a built in wrapper for
System.Xml.Serialization.XmlSerializer
namedDotNetXmlSerializer
, it's just not used by default. To use it, just add the following line:在最近的一个项目中,我使用 XElement(来自 System.Xml.Linq 程序集)来手动构建我的请求。不过,我只有少数财产需要处理。 RestSharp 解决了反序列化来自服务器的大型 XML 图形响应的实际问题。
如果您的对象模型与 XML 模式不同,您将必须创建另一个对象模型并映射到该模型,以便可以使用某些库自动序列化它。在这种情况下,您最好手动映射到模式。
On a recent project I used XElement (from the System.Xml.Linq assembly) to manually build up my requests. I only had a handful of properties to deal with though. RestSharp solved the real problem which was deserializing the large XML graph responses from the server.
If your object model is dissimilar to XML schema you will have to create another object model, and map to that, just so it can be serialized automagically, using some library. In that situation you may be better off manually mapping to the schema.
RestSharp 支持一些基本的 XML 序列化,您可以根据需要覆盖它们:
RestSharp supports some basic XML serialization, which you can override if needed: