dif
dif

Reputation: 2493

Serializing a class to xml using RestSharp.AddBody fails

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";
}
  1. Using RestSharp.Serializers.XmlSerializer() I get: "<Dummy />" (missing both strings)

  2. Using RestSharp.Serializers.DotNetXmlSerializer() I get nothing, the programm just dosen't get over the serialization-step.

  3. 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!

Upvotes: 1

Views: 4693

Answers (1)

John Sheehan
John Sheehan

Reputation: 78114

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.

Upvotes: 1

Related Questions