如何在ASP.NET Core 3中设置JSON序列化程序设置?

时间:2019-10-15 10:00:49

标签: c# json asp.net-core .net-core asp.net-core-3.0

旧版asp.net核心应用程序的

json序列化程序设置是通过添加AddMvc().AddJsonOptions()来设置的,但是我没有在AddMvc()中使用asp.net core 3。那么如何设置全局json序列化设置?

4 个答案:

答案 0 :(得分:14)

AddMvc返回一个IMvcBuilder实现,它具有相应的AddJsonOptions扩展方法。新型方法AddControllersAddControllersWithViewsAddRazorPages也返回IMvcBuilder的实现。用与AddMvc链接的方式相同,将它们链接:

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

请注意,这里的options不再用于Json.NET,而是用于更新的System.Text.Json API。如果您仍然想使用Json.NET,请参见tymtam's answer

答案 1 :(得分:8)

AddControllers

这仍然是MVC,并且需要Microsoft.AspNetCore.Mvc.NewtonsoftJson nuget程序包,但是您说您使用的是AddContollers

来自Add Newtonsoft.Json-based JSON format support

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

其他选项

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

JsonConvert.DefaultSettings Property

  

获取或设置一个函数,该函数创建默认的JsonSerializerSettings。默认设置由JsonConvert上的序列化方法自动使用,而JToken上的ToObject()和FromObject(Object)自动使用。要在不使用任何默认设置的情况下进行序列化,请使用Create()创建一个JsonSerializer。

答案 2 :(得分:3)

不必添加Newtonsoft,在.Net Core 3.0项目上添加Newtonsoft兼容性软件包是一个很大的问题。

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

当然,有人会庆祝财产命名PascalCase,目前不适用... 因此,null的{​​{1}}表示PascalCase,显然不是很好。

PropertyNamingPolicy

答案 3 :(得分:0)

您可以尝试System.Text.Json,这是新发布的Json nuget软件包转换器。 Newtonsoft在.Net Core中不再能很好地工作。 如下所示的Startup.cs 您可以在configirationSetting方法中编写此代码。

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