为 Refit 客户端设置 JSON 命名约定

Set JSON Naming Convention for Refit client

我正在尝试使用 Refit 库 (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)。如何为 SystemTextJsonContentSerializer 完成此操作?

为了使用 System.Text.JsonRefits source code 有一个 SystemTextJsonContentSerializer class 的 public 构造函数,它接受一个 JsonSerializerOptions 对象并设置例如:

/// <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;
}

因为 RefitSettings class constructor 包含 IHttpContentSerializer,并且由于 SystemTextJsonContentSerializer class(以及 NewtonsoftJsonContentSerializer class ) 实现所述接口,你应该能够做到:

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