【问题标题】:How to set json serializer settings in asp.net core 3?如何在 asp.net core 3 中设置 json 序列化程序设置?
【发布时间】:2022-02-18 05:11:18
【问题描述】:

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

【问题讨论】:

  • 如果你不使用AddMvc,你会做什么?你在使用例如AddControllers 或者你根本不使用 MVC?
  • @KirkLarkin 我使用默认方式构建 asp.net core 3 应用程序 - app.UseEndpoints(endpoints => { endpoints.MapControllers() })services.AddControllers();
  • 好吧,我猜你在ConfigureServices 中使用AddControllers,对吧?
  • @KirkLarkin,是的,对

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


【解决方案1】:

AddMvc 返回一个IMvcBuilder 实现,它有一个对应的AddJsonOptions 扩展方法。新式方法AddControllersAddControllersWithViewsAddRazorPages 也返回IMvcBuilder 实现。以与AddMvc 链接相同的方式链接这些:

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

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

【讨论】:

  • 添加“options.JsonSerializerOptions.IgnoreNullValues = true;”没有效果
  • 致其他点击此页面寻找枚举转换的人:[JsonConverter(typeof(JsonStringEnumConverter))] public enum SomeEnum
  • 对于 ASP.NET Core 3.1(2021 年 5 月),我们可以指定以下内容以通过 startup.cs 文件要求 JSON 序列化程序不要序列化空值: services.AddControllers() .AddJsonOptions( options => options.JsonSerializerOptions.IgnoreNullValues = true);
【解决方案2】:

选项 A. AddControllers

这仍然是 MVC,需要 Microsoft.AspNetCore.Mvc.NewtonsoftJson nuget 包,但你说你使用AddControllers

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

选项 B. 默认设置

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

JsonConvert.DefaultSettings Property

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

【讨论】:

  • 您好,这是在 Json.NET 级别上设置的,如何在 ASP.NET 级别上进行设置?
  • 它在 ASP.NET 级别配置设置,这意味着现在使用 NewtonsoftJson 序列化程序进行默认 ModelBinding。
  • 谢谢,选项 A 对我有用。从 2.2 升级到 3.1,我的端点坏了,因为 System.Text.Json 没有正确处理多态性或枚举。更改默认序列化程序的好方法。
  • 忽略空值并将枚举转换为字符串的示例:services.AddControllersWithViews().AddNewtonsoftJson(o => { o.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore; o.SerializerSettings.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter()); });
  • 不确定我是否会在新项目中执行此操作,但将旧代码移至新版本... +1 AddNewtonsoftJson() 和文档链接。
【解决方案3】:

不需要添加 Newtonsoft,在 .Net Core 3.0 项目中添加 Newtonsoft 兼容包是个问题。

另见https://github.com/aspnet/AspNetCore/issues/13564

当然,现在人们会庆祝属性命名PascalCase, NA... 所以null for PropertyNamingPolicy 表示PascalCase,显然不是很好。

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

【讨论】:

  • 谢谢@OSP,但是“显然不是很好”到底是什么意思?
【解决方案4】:

你可以试试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 ());
      });  

【讨论】:

  • 1.不是那么新 2.您能否解释一下声明“Newtonsoft 在.Net Core 中不再工作得很好”? 3.什么是“configirationSetting方法”
  • 你好@GuruStron,1)它是新的,因为它支持net core 3.1库。 (devblogs.microsoft.com/dotnet/try-the-new-system-text-json-apis) 2) (docs.microsoft.com/en-us/dotnet/standard/serialization/…) 3) 微软现在在所有软件中使用来自其自己的框架的新 nuget 包。出于这个原因,它撤回了许多人的支持,并将他们引导到他们自己的包中。 Newtonsoft.Json 提供支持,但现在 Microsoft 想要自己的 Core 包。
  • 1) 您在这一点上链接的文章大约有 1.5 年的历史 2) 这一篇是关于如何迁移的,没有解释问题中的声明 =)) 3) 这一点没有回答问题"什么是"configirationSetting方法"" =)
【解决方案5】:

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

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

2。添加 Startup.cs :

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

【讨论】:

    【解决方案6】:

    .net6 中,在 program.cs 文件中的 .AddControllers() 之后添加此代码:

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

    【讨论】:

    • 问题是关于net 3.1
    猜你喜欢
    • 1970-01-01
    • 2017-12-03
    • 2013-01-13
    • 2020-04-01
    • 2014-03-15
    • 2021-11-22
    相关资源
    最近更新 更多