Pranav Kumar
Pranav Kumar

Reputation: 259

Swagger UI is not using Newtonsoft.Json to serialize decimal, instead using System.Text.json

When the decimal value of "Salary" field of below POCO class is 12000M (a decimal value), the Swagger UI displays the JSON attribute values as 12000. Whereas, the expected JSON attribute values as 12000.0 (i.e. having a trailing zero).

Used the following code inside "ConfigureServices(IServiceCollection services)" method of startup.cs:

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

Used the following code snippet as well, but the expected output is not coming in Swagger UI. (in Swashbuckle.AspNetCore.Newtonsoft V6.1.4.0)

services.AddAwaggerGenNewtonsoftSupport();

When the above code snippet didn't work, tried following as well. But there is no luck.

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

Class:

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

It looks like, even after adding the above code snippet, the Swagger UI is not using Newtonsoft.Json to serialize decimal, instead using System.Text.json.

.Net Core Version is 3.1

Upvotes: 1

Views: 5376

Answers (1)

Roni Stiawan
Roni Stiawan

Reputation: 71

Install this package

Install-Package Swashbuckle.AspNetCore.Newtonsoft -Version 6.2.3

Then add this line

builder.Services.AddSwaggerGenNewtonsoftSupport();

Upvotes: 7

Related Questions