After comparing the JsonConverterAttribute definition in Newtonsoft.Json and System.Text.Json.Serialization, we can find that: when using the System.Text.Json.Serialization, it doesn't allow to enter the converter parameters.
![enter image description here]()
So, as dbc said, you could create a Custom JsonConverter to convert the decimal with 3 digits, like this:
public class MyDecimalConverter3Digit : JsonConverter<decimal>
{
public override decimal Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
throw new NotImplementedException();
}
public override void Write(Utf8JsonWriter writer, decimal value, JsonSerializerOptions options)
{
writer.WriteStringValue(Decimal.Round(value, 3).ToString());
}
}
Then, register the JsonConverter in Startup.ConfigureServices method:
services.AddControllersWithViews().AddJsonOptions(options =>
{
options.JsonSerializerOptions.Converters.Add(new MyDecimalConverter3Digit());
});
After that you could use it in the model, like this:
public class Calculate
{
public decimal Price { get; set; }
[JsonConverter(typeof(MyDecimalConverter3Digit))]
public decimal Rate { get; set; }
}
Besides, you could also configure your application to use the Newtonsoft.Json serialize and deserialize json. Please refer the following steps:
Install the Microsoft.AspNetCore.Mvc.NewtonsoftJson package via NuGet or use the following command:
Install-Package Microsoft.AspNetCore.Mvc.NewtonsoftJson
Add .AddNewtonsoftJson() method at the end of the AddControllersWithViews(), like this:
services.AddControllers().AddNewtonsoftJson();
services.AddControllersWithViews().AddNewtonsoftJson();
services.AddRazorPages().AddNewtonsoftJson();
When you create custom converter, remember to use the Newtonsoft reference, instead of System.Text.Json.Serialization. Like this:
![enter image description here]()
After that, you could use the custom converter with parameters.