Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RestSharp RestRequest.AddBody not using Newton.Json attributes

Tags:

c#

restsharp

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?

like image 467
Ryan Fisch Avatar asked Mar 12 '13 20:03

Ryan Fisch


2 Answers

I have used an answer of tafaju and implemented my serializer for json like this.

public class CustomJsonSerializer : ISerializer
{
    public CustomJsonSerializer()
    {
        ContentType = "application/json";
    }

    public string Serialize(object obj)
    {
        return JsonConvert.SerializeObject(obj);
    }

    public string RootElement { get; set; }

    public string Namespace { get; set; }

    public string DateFormat { get; set; }

    public string ContentType { get; set; }

}

And it works perfectly for me, it reads attributes and serializes all types correctly. But I didn't test it with all types. Documentation says that RootElement, Namespace, DateFormat aren't used for json.

like image 55
prime_z Avatar answered Oct 21 '22 21:10

prime_z


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

like image 5
Ryan Fisch Avatar answered Oct 21 '22 19:10

Ryan Fisch