RestSharp RestRequest.AddBody not using Newton.Json attributes

Ryan Fisch picture Ryan Fisch · Mar 12, 2013 · Viewed 7.1k times · Source
var obj = new MyObject();

I am having an issue getting RestSharp RestRequest.AddBody(obj); to serialize the object correctly.

class MyObject
{
   [JsonProperty(PropertyName="a")]
   public A{get;set;}

   [JsonProperty(PropertyName="b")]
   public B{get;set;}
}

problem is the AddBody serializer is not taking into account my JsonProperty attributes and I can seem to figure out how to set the serializer on the RestRequest or the RestClient?

Answer

Ryan Fisch picture Ryan Fisch · Mar 12, 2013

I found following link which resolved the issue of a lack of attribute support RestSharp Deserialization

Overriding the default serializers

When making requests with XML or JSON request bodies, you can specify your own implementation of ISerializer to use.

var request = new RestRequest();
request.RequestFormat = RequestFormat.Xml;
request.XmlSerializer = new SuperXmlSerializer(); // implements ISerializer
request.AddBody(person); // object serialized to XML using your custom serializer;

And implemented the following class to override the default JsonSerializer New Json Serializer