在 ASP.NET Core 3 中是否有使用蛇形大小写作为 JSON 命名策略的内置方式? [英] Is there a built in way of using snake case as the naming policy for JSON in ASP.NET Core 3?

查看:27
本文介绍了在 ASP.NET Core 3 中是否有使用蛇形大小写作为 JSON 命名策略的内置方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I managed to get it working using the following code:

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

然而,这使得 MVC 使用 Newtonsoft 而不是 System.Text.JSON,后者更快、异步且内置.

However this makes MVC use Newtonsoft rather than System.Text.JSON which is faster, async and built in.

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

Looking at the naming policy options in System.Text.JSON I could only find CamelCase. Is there any native support for snake case? What is a better way of achieving snake case JSON naming style?

推荐答案

只需对 pfx 代码稍作修改,即可移除对 Newtonsoft Json.Net 的依赖.

Just slight modification in pfx code to remove the dependency on Newtonsoft Json.Net.

String 扩展方法将给定的字符串转换为SnakeCase.

String extension method to convert the given string to SnakeCase.

public static class StringUtils
{
    public static string ToSnakeCase(this string str)
    {
        return string.Concat(str.Select((x, i) => i > 0 && char.IsUpper(x) ? "_" + x.ToString() : x.ToString())).ToLower();
    }
}

然后在我们的SnakeCaseNamingPolicy中我们可以做

Then in our SnakeCaseNamingPolicy we can do

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

    public override string ConvertName(string name)
    {
        // Conversion to other naming convention goes here. Like SnakeCase, KebabCase etc.
        return name.ToSnakeCase();
    }
}

最后一步是在Startup.cs

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

    public string Summary { get; set; }
}

Json 输出:

{
  "date": "2019-10-28T08:26:14.878444+05:00",
  "temperature_celcius": 4,
  "temperature_fahrenheit": 0,
  "summary": "Scorching"
}

这篇关于在 ASP.NET Core 3 中是否有使用蛇形大小写作为 JSON 命名策略的内置方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆