使用 RestSharp 将 json 密钥生成为 snake_case

Generate json key as snake_case with RestSharp

知道如何使用 RestSharp 生成 json 密钥作为 snake_case 吗?

使用 Newtonsoft.Json,我可以设置 json 输出这样的东西

  DefaultContractResolver contractResolver = new DefaultContractResolver
            {
                NamingStrategy = new SnakeCaseNamingStrategy()
            };

            string json = JsonConvert.SerializeObject(requestData, new JsonSerializerSettings
            {
                ContractResolver = contractResolver,
                Formatting = Formatting.Indented
            });

但我不确定如何使用 RestSharp

var client = new RestClient(getService.MstUrl);

            client.AddDefaultHeader("Authorization", string.Format("Bearer {0}", token));

            var request = new RestRequest(Method.POST).AddJsonBody(requestData);          

            var response = await client.ExecuteAsync(request);

它保持生成为 camelCase。有没有像Newtonsoft.Json?

这样的配置

您应该能够创建自己的 IRestSerializer 实现并在 client.UseSerializer

中提供

给定

public class SimpleJsonSerializer : IRestSerializer
{
   private readonly DefaultContractResolver _contractResolver;

   public SimpleJsonSerializer()
   {
      _contractResolver = new DefaultContractResolver
      {
         NamingStrategy = new SnakeCaseNamingStrategy()
      };   
   }
   public string Serialize(object obj) => JsonConvert.SerializeObject(obj, new JsonSerializerSettings
   {
      ContractResolver = _contractResolver,
      Formatting = Formatting.Indented
   });

   public string Serialize(Parameter bodyParameter) => Serialize(bodyParameter.Value);

   public T Deserialize<T>(IRestResponse response) => JsonConvert.DeserializeObject<T>(response.Content);

   public string[] SupportedContentTypes { get; } =
   {
      "application/json", "text/json", "text/x-json", "text/javascript", "*+json"
   };

   public string ContentType { get; set; } = "application/json";

   public DataFormat DataFormat { get; } = DataFormat.Json;
}

用法

var client = new RestClient(getService.MstUrl);

client.AddDefaultHeader("Authorization", string.Format("Bearer {0}", token));
client.UseSerializer(() => new SimpleJsonSerializer(){});

var request = new RestRequest(Method.POST).AddJsonBody(requestData);

var response = await client.ExecuteAsync(request);

免责声明 :我已经很多年没用过 RestSharp 了,以后也不打算再用了。此外,我确实建议任何想使用它的人切换回 HttpClient,甚至更好的 IHttpClientFactory。更重要的是,这是完全未经测试的,仅作为示例给出。您可能需要根据需要对其进行修改

使用 RestSharp,并不意味着您也不能使用 Newtonsoft 序列化程序。

来自restsharp documentation

RestSharp support Json.Net serializer via a separate package. You can install it from NuGet.

client.UseNewtonsoftJson();

并继续你所做的:

DefaultContractResolver contractResolver = new DefaultContractResolver
{
    NamingStrategy = new SnakeCaseNamingStrategy()
};