Restsharp - 如何将枚举列表序列化为字符串 [英] Restsharp - how to serialize a list of enums to strings
问题描述
我有一个 List
属性在我使用 RestSharp 序列化为 XML 的类中作为请求的主体.我希望输出为:
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>
我想将枚举值转换为字符串并删除自动添加的容器元素.这可以用 RestSharp 吗?我认为属性可能是可能的,但显然不是.我是否必须自己使用自定义序列化程序来处理此输出?
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}
}
并序列化为请求
var req = new RestSharp.RestRequest(RestSharp.Method.POST);
req.RequestFormat = RestSharp.DataFormat.Xml;
req.AddQueryParameter("REST-PAYLOAD", "");
req.AddXmlBody(myBar);
推荐答案
您可以使用内置的 RestSharp 的 DotNetXmlSerializer
使微软的 XmlSerializer
执行实际的序列化.然后您可以使用 XML 序列化属性来指定<Bar
的 code>List[XmlElement]
:
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);
注意 Bar
必须是公共的,因为 XmlSerializer
只能序列化公共类型.
Note that Bar
must be public because XmlSerializer
can only serialize public types.
这篇关于Restsharp - 如何将枚举列表序列化为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!