Home > Mobile >  My json keys are getting converted to lowercase once I POST it via RestSharp
My json keys are getting converted to lowercase once I POST it via RestSharp

Time:05-18

Here is my code :

    request.AddHeader("Content-Type", "application/json; charset=utf-8");
    request.RequestFormat = DataFormat.Json;

    request.AddJsonBody(new
    {
       

        AccountName= "Some account name",
        AccountStatus= true
    });

    request.AddParameter("Content-Type", "application/json; charset=utf-8", ParameterType.RequestBody);

    request.RequestFormat = DataFormat.Json;

    response = client.ExecutePostAsync(request).Result;
    Console.WriteLine(response.Content.ToString());

}

And Response I am getting is : 400 (Bad Request)

And then from the server log , I got to know that above code does not maintain Camel case of json Keys. It sends as accountname instead of AcconutName. Same for AccountStatus.

CodePudding user response:

RestSharp uses the default options for JSON serialization in the Web context. You can change these for the client:

var options = new JsonSerializerOptions(JsonSerializerDefaults.Web);
options.PropertyNamingPolicy = null;
client.UseSystemTextJson(options);

The above sample still uses the default options for web, but removes the PropertyNamingPolicy that is responsible for serializing property names as camel-case.

  • Related