我将默认 JsonSerializer 设置为 Utf8Json

Ori*_*ael 4 c# serialization asp.net-core utf8json

使用 c# 8 和 .netcore 3.1。

我在这里读到Utf8Json库处理json 序列化和反序列化的速度比NewtonsoftJson更快。

我们最近将服务器代码从.netcore 2.2 升级到 3.1,主要是为了提高性能。因此,我们也使用最好的序列化库是合理的。

所以我的问题是:

  1. 里面Startup.cs有这个

    services.AddControllers().AddNewtonsoftJson(options =>
    {
        options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
    });
    
    Run Code Online (Sandbox Code Playgroud)

我希望它使用不同的库,所以我发现我可以使用,.AddJsonOptions但我无法弄清楚如何设置默认序列化器,即使在使用我的 google-fu 技能之后也是如此。

  1. 由于我一直[JsonProperty("<name>")]在代码中到处使用以减少 json 字符串大小,我是否需要为新序列化器格式化所有内容,或者有没有办法让他考虑 property 属性?(属性为Newtonsoft)

谢谢。

Pra*_*a M 5

@Ori你可以在net core 3.1项目中使用Utf8json。

使用

[DataMember(Name = "RoleType")] public string Role_Type { get; set; }

代替

[JsonProperty("<name>")]

要在 Asp.Net core 中使用 Utf8json 格式化程序,您需要添加如下所述的格式化程序。

    public void ConfigureServices(IServiceCollection services)
{
    services.AddControllersWithViews()


    // Add Utf8Json formatters
    .AddMvcOptions(option =>
    {
        option.OutputFormatters.Clear();
        option.OutputFormatters.Add(new JsonOutputFormatter (StandardResolver.Default));
        option.InputFormatters.Clear();
        option.InputFormatters.Add(new JsonInputFormatter ());
    });
}
Run Code Online (Sandbox Code Playgroud)

您还可以参考下面的链接了解格式化程序。 https://github.com/neuecc/Utf8Json/blob/master/src/Utf8Json.AspNetCoreMvcFormatter/Formatter.cs

我正在使用 utf8json,它对我们来说非常有用。