如何使用 System.Text.Json 将对象属性序列化为小写?

How do I serialize object properties to lower case using System.Text.Json?

我有一个 ASP.NET 5 MVC 核心应用程序控制器,其中包含以下代码:

using System.Text.Json;

public async Task<IActionResult> EstoAPICall() {
  ...
  EstoOst estoOst;
  var json = JsonSerializer.Serialize(estoOst);
  StringContent content = new(json, Encoding.UTF8, "application/json");
  using var response = await httpClient.PostAsync("https://example.com", content);
  ...
}

public class EstoOst {
  public decimal Amount { get; set; }
}

这会导致错误,因为 API 在 JSON 中需要小写 amount,但 .Serialize(...) 返回大写 Amount

我该如何解决这个问题?

切换到 Json.NET,或将 class 属性 名称更改为小写似乎不是好的解决方案。

如果您真的正在寻找全小写属性名字而不是驼峰式属性名字例如FullName 变为 fullname 而不是 fullName,没有内置的东西 - 您必须像这样创建自己的 JsonNamingPolicy

LowerCaseNamingPolicy.cs

public class LowerCaseNamingPolicy : JsonNamingPolicy
{
  public override string ConvertName(string name)
  {
      if (string.IsNullOrEmpty(name) || !char.IsUpper(name[0]))
          return name;

      return name.ToLower();
  }
}

用法:

var options = new JsonSerializerOptions {
    PropertyNamingPolicy = new LowerCaseNamingPolicy(),
};

var json = JsonSerializer.Serialize(estoOst, options);

但是,考虑到您提到的 Json.NET 也没有小写命名策略,我认为您正在寻找驼峰式命名

如果是这样,请设置 JsonSerializerOptions.PropertyNamingPolicy property to JsonNamingPolicy.CamelCase 以将 属性 名称序列化为驼峰格式:

var options = new JsonSerializerOptions {
    PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
};

var json = JsonSerializer.Serialize(estoOst, options);

这是一个工作演示,用于输出并显示两种方法的输出差异:

public class Program
{
  public static void Main()
  {
      var person = new Person
      {
          Age = 100,
          FullName = "Lorem Ipsum"
      };

      var camelCaseJsonSerializerOptions = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase };
      var lowercaseJsonSerializerOptions = new JsonSerializerOptions { PropertyNamingPolicy = new LowerCaseNamingPolicy()};

      var camelCaseJson = JsonSerializer.Serialize(person, camelCaseJsonSerializerOptions);
      var lowercaseJson = JsonSerializer.Serialize(person, lowercaseJsonSerializerOptions);

      Console.WriteLine(camelCaseJson);
      Console.WriteLine(lowercaseJson);
  }
}

public class Person
{
  public string FullName { get; set; }
  public int Age { get; set; }
}

public class LowerCaseNamingPolicy : JsonNamingPolicy
{
  public override string ConvertName(string name)
  {
      if (string.IsNullOrEmpty(name) || !char.IsUpper(name[0]))
          return name;

      return name.ToLower();
  }
}

输出:

{"fullName":"Lorem Ipsum","age":100}
{"fullname":"Lorem Ipsum","age":100}