简体   繁体   English

如何在 asp.net 内核 3 中设置 json 串行器设置?

[英]How to set json serializer settings in asp.net core 3?

json serializer settings for legacy asp.net core applications were set by adding AddMvc().AddJsonOptions() , but I don't use AddMvc() in asp.net core 3 .传统 asp.net 核心应用程序的 json 序列化程序设置是通过添加AddMvc().AddJsonOptions()来设置的,但我不在 Z1848E732214CCE460F9B24F0C28 中使用asp.net core 3 AddMvc() So how can I set global json serialization settings?那么如何设置全局 json 序列化设置呢?

AddMvc returns an IMvcBuilder implementation, which has a corresponding AddJsonOptions extension method. AddMvc返回一个IMvcBuilder实现,它有一个对应的AddJsonOptions扩展方法。 The new-style methods AddControllers , AddControllersWithViews , and AddRazorPages also return an IMvcBuilder implementation.新式方法AddControllersAddControllersWithViewsAddRazorPages也返回一个IMvcBuilder实现。 Chain with these in the same way you would chain with AddMvc :以与AddMvc链接相同的方式链接这些:

services.AddControllers()
    .AddJsonOptions(options =>
    {
        // ...
    });

Note that options here is no longer for Json.NET, but for the newer System.Text.Json APIs.请注意,此处的options不再适用于 Json.NET,而是适用于较新的System.Text.Json API。 If you still want to use Json.NET, see tymtam's answer如果您仍想使用 Json.NET,请参阅tymtam 的回答

Option A. AddControllers选项 A. AddControllers

This is still MVC, and requires Microsoft.AspNetCore.Mvc.NewtonsoftJson nuget package, but you said you use AddControllers .这仍然是 MVC,并且需要 Microsoft.AspNetCore.Mvc.NewtonsoftJson nuget package,但您说您使用AddControllers

From Add Newtonsoft.Json-based JSON format support添加基于 Newtonsoft.Json 的 JSON 格式支持

services.AddControllers().AddNewtonsoftJson(options =>
{
    // Use the default property (Pascal) casing
    options.SerializerSettings.ContractResolver = new DefaultContractResolver();

    // Configure a custom converter
    options.SerializerOptions.Converters.Add(new MyCustomJsonConverter());
});

Option B. DefaultSettings选项 B. 默认设置

JsonConvert.DefaultSettings = () => new JsonSerializerSettings (...)

JsonConvert.DefaultSettings Property JsonConvert.DefaultSettings 属性

Gets or sets a function that creates default JsonSerializerSettings.获取或设置创建默认 JsonSerializerSettings 的 function。 Default settings are automatically used by serialization methods on JsonConvert, and ToObject () and FromObject(Object) on JToken. JsonConvert 上的序列化方法以及 JToken 上的 ToObject () 和 FromObject(Object) 会自动使用默认设置。 To serialize without using any default settings create a JsonSerializer with Create().要在不使用任何默认设置的情况下进行序列化,请使用 Create() 创建一个 JsonSerializer。

Adding Newtonsoft is not necessary, quite a problems with adding Newtonsoft compatibility packages on.Net Core 3.0 project.添加 Newtonsoft 不是必须的,在 .Net Core 3.0 项目上添加 Newtonsoft 兼容包是个很大的问题。

See also https://github.com/aspnet/AspNetCore/issues/13564另请参阅https://github.com/aspnet/AspNetCore/issues/13564

Of course, one would celebrate property naming PascalCase , NA at the moment... So null for PropertyNamingPolicy means PascalCase, which is obviously not very good.当然,现在人们会庆祝属性命名PascalCase , NA ......所以PropertyNamingPolicynull表示 PascalCase,这显然不是很好。

// Pascal casing
services.AddControllersWithViews().
        AddJsonOptions(options =>
        {
            options.JsonSerializerOptions.PropertyNameCaseInsensitive = true;
            options.JsonSerializerOptions.PropertyNamingPolicy = null;
        });

You can try System.Text.Json , the newly released Json nuget package converter.可以试试System.Text.Json ,新发布的 Json nuget ZEFE90A8E6304A7F6B70D8转换器。 Newtonsoft no longer works very well in.Net Core. Newtonsoft 在.Net Core 中不再工作得很好。 Startup.cs as below You can write this code inside the configirationSetting method. Startup.cs 如下您可以在 configirationSetting 方法中编写此代码。

 services.AddControllers()
     .AddJsonOptions(options =>
      {
          options.JsonSerializerOptions.PropertyNameCaseInsensitive = true;
          options.JsonSerializerOptions.PropertyNamingPolicy = null;
          options.JsonSerializerOptions.Converters.Add (new JsonStringEnumConverter ());
      });  

1.install NuGet: Microsoft.AspNetCore.Mvc.NewtonsoftJson or 1.安装 NuGet: Microsoft.AspNetCore.Mvc.NewtonsoftJson 或

   <ItemGroup>
        <PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="3.1.2" />
    </ItemGroup>

2. Add Startup.cs: 2.添加Startup.cs:

   public void ConfigureServices(IServiceCollection services)
     {
         //JSON Serializer
         services.AddControllers().AddNewtonsoftJson(options =>
           {
            options.SerializerSettings.ReferenceLoopHandling = 
               Newtonsoft.Json.ReferenceLoopHandling.Ignore;
           });
    }

In .net6 add this code after .AddControllers() in program.cs file:.net6中,在program.cs文件中的.AddControllers()之后添加此代码:

builder.Services.AddControllers().AddJsonOptions(options => { options.JsonSerializerOptions.PropertyNamingPolicy = null; }); builder.Services.AddControllers().AddJsonOptions(options => { options.JsonSerializerOptions.PropertyNamingPolicy = null; });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM