2

I'm trying to use the Refit library (https://github.com/reactiveui/refit) to create an http client for my service, but there was a problem. I want to use SystemTextJsonContentSerializer for serialization and set the naming convention of json object properties for the request body. However, I did not find in the documentation how to do this. There is only an example for NewtonsoftJsonContentSerializer (see https://github.com/reactiveui/refit#json-content). How can this be done for SystemTextJsonContentSerializer?

kaboom
  • 41
  • 5

1 Answers1

3

For using System.Text.Json, Refits source code has a public constructor for the SystemTextJsonContentSerializer class that takes in a JsonSerializerOptions object and sets it for the instance:

/// <summary>
/// Creates a new <see cref="SystemTextJsonContentSerializer"/> instance with the specified parameters
/// </summary>
/// <param name="jsonSerializerOptions">The serialization options to use for the current instance</param>
public SystemTextJsonContentSerializer(JsonSerializerOptions jsonSerializerOptions)
{
      this.jsonSerializerOptions = jsonSerializerOptions;
}

Because the RefitSettings class constructor takes in a IHttpContentSerializer, and since the SystemTextJsonContentSerializer class (and the NewtonsoftJsonContentSerializer class for that matter) implements said interface, you should be able to do:

var jsonSerializerOptions = new JsonSerializerOptions 
{
    //set some options such as your preferred naming style...
    PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
    WriteIndented = true
};

var settings = new RefitSettings(new SystemTextJsonContentSerializer(jsonSerializerOptions), null, null); 
//the two null parameters are for IUrlParameterFormatter? and IFormUrlEncodedParameterFormatter? objects
Timothy G.
  • 6,335
  • 7
  • 30
  • 46