RestSharp - how to influence JSON serialization (naming)?
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.
marc_s
Note to all SO beginner: please absolutely read Jon Skeet's helpful hints on how to write a good question (or at least his short version here) - one that has a chance that someone can answer it. A senior C# / SQL Server / Entity Framework backend developer for line-of-business applications (mostly ASP.NET / ASP.NET Core).
Updated on June 16, 2022Comments
-
marc_s almost 2 years
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?
-
Marcel almost 5 yearsNow, that RestSharp got rid of the Json.NET dependeny (as per Version 103 (github.com/restsharp/RestSharp/blob/master/readme.txt)), is this sill the way to go today?
-
aloisdg almost 5 years@Marcel I don't know. Consider my answer as outdated