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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With