开发者

Serialize an object when posting data with RestSharp

开发者 https://www.devze.com 2023-03-21 05:41 出处:网络
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

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 reser开发者_C百科ialize? 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.


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:

[XmlElement(ElementName = "short-name")]
[SerializeAs(Name = "short-name")]
public string shortName { get; set; }

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.


After looking at the source code for RestSharp I found that they actually have a built in wrapper for System.Xml.Serialization.XmlSerializer named DotNetXmlSerializer, it's just not used by default. To use it, just add the following line:

var request = new RestRequest();
request.RequestFormat = RequestFormat.Xml;
request.XmlSerializer = new DotNetXmlSerializer();
request.AddBody(someObject);


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 supports some basic XML serialization, which you can override if needed:

var request = new RestRequest();
request.RequestFormat = RequestFormat.Xml;
request.XmlSerializer = new SuperXmlSerializer(); // optional override, implements ISerializer
request.AddBody(person); // object serialized to XML using current XML serializer
0

精彩评论

暂无评论...
验证码 换一张
取 消