Serialize an object when posting data with RestSharp

匆匆过客 提交于 2019-12-01 04:22:30
tor.flatebo

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