Serializing a class to xml using RestSharp.AddBody fails
-
26-10-2019 - |
题
I try to add a simple test-class to a RestSharp-RestRequest
via the RestRequest.AddBody
-Method. I tried to serialize using both of the delivered serializers, but i could not get one of them to work (JSON-Serializations works pretty fine with just the same settings...)
This is how i do the serialization:
private void SerializationTest()
{
RestRequest request = new RestRequest();
request.XmlSerializer = new RestSharp.Serializers.DotNetXmlSerializer();
//request.XmlSerializer = new RestSharp.Serializers.XmlSerializer();
request.RequestFormat = DataFormat.Xml;
//request.RequestFormat = DataFormat.Json;
request.AddBody(new Dummy()); // uses JsonSerializer
label1.Text = request.Parameters[0].Value.ToString();
}
The dummy-class I'm using is:
private class Dummy
{
public string A = "Some string";
public string B = "Some string";
}
Using
RestSharp.Serializers.XmlSerializer()
I get: "<Dummy />
" (missing both strings)Using
RestSharp.Serializers.DotNetXmlSerializer()
I get nothing, the programm just dosen't get over the serialization-step.Using JSON
request.RequestFormat = DataFormat.Json;
, everything works fine.
.
{
"A": "Some string",
"B": "Some string"
}
How do i get the class so serialize proper to XML?
Thanks for your help!
解决方案
Those are fields, not properties. The underlying XmlSerializer only looks for public properties. Update it to this and it should work:
class Dummy
{
public string A { get; set; };
public string B { get; set; };
public Dummy() {
A = "Some string";
B = "Some string";
}
}
The reason the JSON one works is because it defers to JSON.NET's default serializer which (apparently) supports fields. I think this is the wrong design decision personally.