【问题标题】:Swagger UI is not using Newtonsoft.Json to serialize decimal, instead using System.Text.jsonSwagger UI 不使用 Newtonsoft.Json 序列化十进制,而是使用 System.Text.json
【发布时间】:2021-09-21 00:18:46
【问题描述】:

当 POCO 类以下的“Salary”字段的十进制值为 12000M(十进制值)时,Swagger UI 将 JSON 属性值显示为 12000。 而预期的 JSON 属性值为 12000.0(即尾随零)

在startup.cs的“ConfigureServices(IServiceCollection services)”方法中使用了如下代码:

services.AddControllers().AddNewtonsoftJson(options =>
{
    options.SerializerSettings.FloatParseHandling = FloatParseHandling.Decimal;
    options.SerializerSettings.FloatFormatHandling = FloatFormatHandling.DefaultValue;
});
services.AddControllersWithViews().AddNewtonsoftJson(options =>
{
    options.SerializerSettings.FloatParseHandling = FloatParseHandling.Decimal;
    options.SerializerSettings.FloatFormatHandling = FloatFormatHandling.DefaultValue;
});

也使用了以下代码 sn-p,但 Swagger UI 中没有出现预期的输出。 (在 Swashbuckle.AspNetCore.Newtonsoft V6.1.4.0 中)

services.AddAwaggerGenNewtonsoftSupport();

当上面的代码 sn-p 不起作用时,也尝试跟随。 但是没有运气。

services.AddMvc().AddNewtonsoftJson(options =>
    {
        options.SerializerSettings.FloatParseHandling = FloatParseHandling.Decimal;
        options.SerializerSettings.FloatFormatHandling = FloatFormatHandling.DefaultValue;
    });

类:

public class Employee{
   public string EmployeeName {get; set;}
   public decimal Salary {get; set;}
   public string Department {get; set;}
}

看起来,即使添加了上述代码 sn-p,Swagger UI 也没有使用 Newtonsoft.Json 序列化十进制,而是使用 System.Text.json。

.Net Core 版本为 3.1

【问题讨论】:

    标签: asp.net-core json.net swagger-ui jsonserializer system.text.json


    【解决方案1】:

    安装这个包

    Install-Package Swashbuckle.AspNetCore.Newtonsoft -Version 6.2.3
    

    然后添加这一行

    builder.Services.AddSwaggerGenNewtonsoftSupport();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-03-13
      • 2021-06-23
      • 2021-02-23
      • 2021-12-08
      • 2016-06-18
      • 2021-09-30
      • 2021-11-21
      相关资源
      最近更新 更多