c# - 在 ASP.NET Core 3 中,是否有使用蛇形大小写作为 JSON 命名策略的内置方式?

标签 c# asp.net-core .net-core .net-core-3.0 system.text.json

我设法使用以下代码使其工作:

.AddNewtonsoftJson(options => {
    options.SerializerSettings.ContractResolver = new DefaultContractResolver
    {
        NamingStrategy = new SnakeCaseNamingStrategy()
    };
});

然而这使得 MVC 使用 Newtonsoft而不是 System.Text.JSON这是更快,异步和内置。

查看 System.Text.JSON 中的命名策略选项我只能找到 CamelCase。是否有对蛇盒的本地支持?什么是实现蛇案例 JSON 命名风格的更好方法?

最佳答案

目前没有对蛇盒的内置支持,
但是 .NET Core 3.0允许设置 自定义命名策略 通过继承 JsonNamingPolicy .

您需要实现 ConvertName方法与蛇大小写转换。
(Newtonsoft Json.NET 有一个内部 StringUtils 类,它展示了如何处理这个。)

下面的 POC 实现重用了 Json.NET 的 SnakeCaseNamingStrategy仅用于蛇形大小写转换(而整个应用程序使用 System.Text.Json )。

最好避免仅依赖 Newtonsoft Json.Net 进行蛇形大小写转换,但在下面这个相当懒惰的示例中,我不想重新思考/重新发明蛇形大小写转换方法。
这个答案的要点是如何 Hook 自定义策略(而不是蛇形转换本身。)
(有许多图书馆和 code samples 展示了如何这样做。)

public class SnakeCaseNamingPolicy : JsonNamingPolicy
{
    private readonly SnakeCaseNamingStrategy _newtonsoftSnakeCaseNamingStrategy
        = new SnakeCaseNamingStrategy();

    public static SnakeCaseNamingPolicy Instance { get; } = new SnakeCaseNamingPolicy();

    public override string ConvertName(string name)
    { 
        /* A conversion to snake case implementation goes here. */

        return _newtonsoftSnakeCaseNamingStrategy.GetPropertyName(name, false);
    }
}

Startup.cs您应用此自定义 SnakeCaseNamingPolicy .
public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers()            
        .AddJsonOptions(
            options => { 
                options.JsonSerializerOptions.PropertyNamingPolicy = 
                    SnakeCaseNamingPolicy.Instance;
            });
}

下面类的一个实例
public class WeatherForecast
{
    public DateTime Date { get; set; }

    public int TemperatureCelcius { get; set; }

    public int TemperatureFahrenheit { get; set; }

    [JsonPropertyName("Description")]
    public string Summary { get; set; }
}

会有 Json表示为:
{ "date" : "2019-10-28T01:00:56.6498885+01:00",
  "temperature_celcius" : 48,
  "temperature_fahrenheit" : 118,
  "Description" : "Cool"
}

注意属性Summary已被命名 Description ,
匹配其 System.Text.Json.Serialization.JsonPropertyNameAttribute .

关于c# - 在 ASP.NET Core 3 中,是否有使用蛇形大小写作为 JSON 命名策略的内置方式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58570189/

相关文章:

asp.net - 如何从 ASP.NET Core 中的 Controller 以外的其他类登录?

.net-core - 使用角色 ARN 从 EKS 连接到 SQS

c# - 在 C# 中,为什么在声明 int 时不使用 'new' 关键字?

c# - 在 Xamarin.Android 中执行大量 SQlite 查询失败

c# - 白色 UIAutomation click() 停止在不同平台上工作

c# - 无法分配请求的地址(使用 Docker 时)

c# - 部署到 Azure 应用服务的 WorkerService 未启动

c# - 以编程方式调整 Azure 虚拟机大小的语法

c# - 使用事务内存数据库进行单元测试时,如何抑制 InMemoryEventId.TransactionIgnoredWarning?

docker - 如何在Docker Compose中从服务器设置环境变量?