Serialize an object when sending data using RestSharp

I recently started using RestSharp to use a REST service that uses XML.

This makes deserializing objects from XML to a collection of custom objects trivial. But my question is, what is the best way to reserialize when sending back to the service?

Should I use LINQ-to-XML to reinitialize? I tried using the Serializeable attribute and the utility function of SerializeToXml , but when I do this, it seems to break the deserialization performed by RestSharp.

+6
source share
4 answers

I was able to use attributes to get everything I needed, although my situation is relatively simple. For example, to make deserialize nodes with dashes in them, and then to be able to serialize 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 does not match [XmlElement("elementName")] . Instead, you will need to use [SerializeAs(Name = "elementName")] .

I found this by trolling test code in a RestSharp project.

+3
source

In a recent project, I used XElement (from the System.Xml.Linq assembly) to manually create my queries. Although I had only a few properties. RestSharp solved a real problem that deserialized large XML graph responses from the server.

If your object model does not look like an XML schema, you will have to create another object model and map it so that it can be automatically serialized using some library. In this situation, you might be better off manually matching the pattern.

+1
source

RestSharp supports some basic XML serialization, which you can override if necessary:

 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 
+1
source

Looking at the source code of RestSharp, I found that they actually have a built-in shell for System.Xml.Serialization.XmlSerializer called DotNetXmlSerializer , it is simply not used by default. To use it, simply add the following line:

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

Source: https://habr.com/ru/post/893100/


All Articles