Serialization
Since version 5.0 RestClient uses System.Text.Json for serialization, with stock System.Text.Json behaviour - [JsonPropertyName] attributes are honoured and property matching is case sensitive.
The one place we deviate from stock System.Text.Json is when reading - real world systems are less than perfect and send us less than perfect JSON, so trailing commas and comments are accepted by default.
Upgrading from 4.x? See Upgrading to 5.0 for the breaking changes.
JsonSerializerOptions
Since version 5.0 you can use SetJsonSerializerOptions to provide the JsonSerializerOptions for DalSoft.RestClient to use.
// When directly creating a RestClient instance
dynamic restClient = new RestClient("https://dalsoft.co.uk", new Config()
.SetJsonSerializerOptions(new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower }));
// When using IHttpClientFactory
services
.AddRestClient("MyClient", "https://dalsoft.co.uk")
.SetJsonSerializerOptions(new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower });
Serialization Attributes
On a per class basis you can use System.Text.Json serialization attributes to control DalSoft.RestClient serialization.
public class User
{
[JsonPropertyName("phone_number")]
public string PhoneNumber { get; set; }
}
dynamic restClient = new RestClient("https://jsonplaceholder.typicode.com");
/* https://jsonplaceholder.typicode.com/users/1 response / request body {phone_number:"+44 12345"}; */
User response = await restClient.Users(1).Put(new User { PhoneNumber = "+44 12345" });
//PhoneNumber has JsonPropertyName attribute
Assert.That(response.PhoneNumber, Is.EqualTo("+44 12345"));
You can use System.Text.Json JsonSerializerOptions or serialization attributes to control pretty much anything to do with serialization.
Case sensitive matching
Watch out - property matching is case sensitive, just like System.Text.Json. Models that only deserialized because Json.NET matched case insensitively need the property name mapped:
public class User
{
// jsonplaceholder returns "username" - map the name or the property will be null
[JsonPropertyName("username")]
public string Username { get; set; }
}
If you want case insensitive matching back globally use SetJsonSerializerOptions(new JsonSerializerOptions { PropertyNameCaseInsensitive = true }), or opt in to Json.NET below.
Legacy Json.NET
Before version 5.0 RestClient used Json.NET. If your models rely on the legacy Json.NET behaviour - [JsonProperty] attributes, JsonSerializerSettings, case insensitive matching, lenient date parsing - opt back in with new Config().UseNewtonsoftJson() (optionally passing your JsonSerializerSettings) and you get the 4.x behaviour back exactly. See Upgrading to 5.0.