Search code examples
c#restsharp

Custom Serialization/Deserialization in RestSharp 108


In updating from RestSharp 106 to 108 I've been unable to come up with an elegant replacement for the following. I've looked at the migration documentation to no avail. There is a good chance I've missed something obvious.

Existing code that works in v106, which covered both XML and JSON

Class A

using RestSharp.Deserializers;


[DeserializeAs(Name = "response")]
public class ACertainResponse
{
    public string SomeProp {get; set;}
    //Etc
}

//JSON Payload {"response" : {"SomeProp" : "Some Value"}}

Class B

using RestSharp.Serializers;

[SerializeAs(Name = "request")]
public class SomeRequest
{
    public string SomeProp {get; set;}
    //Etc
}

//Resulting in : 
//{"request" : { "SomeProp" : "A Value" } }

I've found [JsonPropertyName("customName")], however, as the name suggests that is for properties only.


Solution

  • Whilst I was unable to find a one size fits all solution as previouslt provided I was able to get it working by setting attributes for XML or JSON serialization explicitly. These attributes cover bother serialization and deserialization:

    JSON

    using System.Text.Json.Serialization;
    
    [JsonSerializable(typeof(LeadspediaRequest), TypeInfoPropertyName = "response")]
    public class ACertainResponse
    {
        public string SomeProp {get; set;}
        //Etc
    }
    

    XML

    using System.Xml.Serialization;
    
    [XmlRoot(ElementName = "response")]
    [XmlType("response")]
    public class SomeRequest
    {
        public string SomeProp {get; set;}
        //Etc
    }