Serialize an object when posting data with RestSharp

喜你入骨 提交于 2019-12-04 01:24:44

问题


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.


回答1:


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.




回答2:


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);



回答3:


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.




回答4:


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


来源:https://stackoverflow.com/questions/6753663/serialize-an-object-when-posting-data-with-restsharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!