Restsharp - how to serialize a list of enums to strings

孤人 提交于 2020-01-07 02:45:15

问题


I have an List<AnimalsEnum> Foo property in a class that I'm serializing to XML with RestSharp for the body of a request. I'd like the output to be:

<rootNode>
    ... existing content...
    <Foo>Elephant</Foo>
    <Foo>Tiger</Foo>
    .... more content

Instead, for the relevant serialisation part, I have

<Foo>
    <AnimalsEnum />
    <AnimalsEnum />
</Foo>

I'd like to convert the enum values to strings and remove the container element that is automatically added. Is this possible with RestSharp? I thought it may be possible with attributes, but apparently not. Am I going to have to wrangle this output myself with a custom serialiser?

Code is difficult to post, but keeping with the example:

class Bar
{
    public string Name{get;set;}
    public List<AnimalsEnum> Foo{get;set;}
    public enum AnimalsEnum {Tiger,Elephant,Monkey}
}

and to serialize into a request

var req = new RestSharp.RestRequest(RestSharp.Method.POST);
req.RequestFormat = RestSharp.DataFormat.Xml;
req.AddQueryParameter("REST-PAYLOAD", "");
req.AddXmlBody(myBar);

回答1:


You can use the built-in DotNetXmlSerializer of RestSharp to make Microsoft's XmlSerializer do the actual serialization. Then you can use XML serialization attributes to specify that the List<AnimalsEnum> of Bar should be serialized without an outer container element by applying [XmlElement]:

public class Bar
{
    public string Name { get; set; }
    [System.Xml.Serialization.XmlElement]
    public List<AnimalsEnum> Foo { get; set; }
    public enum AnimalsEnum { Tiger, Elephant, Monkey }
}

Then, when making the request, do:

var req = new RestSharp.RestRequest(RestSharp.Method.POST);

// Use XmlSerializer to serialize Bar
req.XmlSerializer = new RestSharp.Serializers.DotNetXmlSerializer(); 

req.RequestFormat = RestSharp.DataFormat.Xml;
req.AddQueryParameter("REST-PAYLOAD", "");
req.AddXmlBody(myBar);

Note that Bar must be public because XmlSerializer can only serialize public types.



来源:https://stackoverflow.com/questions/42129076/restsharp-how-to-serialize-a-list-of-enums-to-strings

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