Search code examples
c#jsonrestsharp

RestSharp - how to influence JSON serialization (naming)?


I am trying to talk to a REST service and I'm trying to call a POST method where I need to provide some data in the post body.

I have my model class all nicely set up something like this:

public class MyRequestClass
{
    public string ResellerId { get; set; }
    public string TransactionId { get; set; }
    ... other properties of no interest here ... 
}

and I'm using RestSharp in C# to call my REST service something like this:

RestClient _client = new RestClient(someUrl);

var restRequest = new RestRequest("/post-endpoint", Method.POST);
restRequest.RequestFormat = DataFormat.Json;
restRequest.AddHeader("Content-Type", "application/json");

restRequest.AddJsonBody(request);   // of type "MyRequestClass"

IRestResponse<MyResponse> response = _client.Execute<MyResponse>(restRequest);

Everything seemed to work fine - no exceptions are thrown. But the service responds with:

We are experiencing problem in processing your request

When I looked at the request JSON that's being sent, I see that all the properties are in Capitalized spelling:

{ "ResellerId":"123","TransactionId":"456" }

and this is causing the issue - the service excepts them in all lowercase:

{ "resellerId":"123","transactionId":"456" }

So I tried to decorate my C# model class with attributes:

public class MyRequestClass
{
    [RestSharp.Serializers.SerializeAs(Name = "resellerId")]
    public string ResellerId { get; set; }

    [RestSharp.Serializers.SerializeAs(Name = "transactionId")]
    public string TransactionId { get; set; }
    ... other properties of no interest here ... 
}

but that didn't seem to change anything - the JSON request sill has the property names in a Capitalized spelling and thus the call fails.

How can I tell RestSharp to always use lowercase property names in the JSON generated from a C# model class?


Solution

  • Edit: this answer is outdated. Read the thread shared by @marc_s. I wont remove this answer because it used to be helpful.

    You can or you should add Json.NET to RestSharp.

    There is a issue about this on the github repo of RestSharp.