Home > front end >  ASP Core Minimal API - How do I send decimals without trailing zeros with System.Text.Json?
ASP Core Minimal API - How do I send decimals without trailing zeros with System.Text.Json?

Time:12-27

I have an ASPNet API server using EF Core 6, and when I use WriteAsJsonAsync to write a decimal property it becomes like: "decimal_property": 0.0000000000000000000000000000. I don't want to trailing zeros.

I found some solutions of custom converts, but they are all written in Newtonsoft rather than System.Text.Json so cannot be used like

builder.Services.Configure<JsonOptions>(opt =>
{
  opt.SerializerOptions.Converters.Add(new DecimalJsonConverter());
}

How to write a DecimalJsonConverter can be injected into WebApplication directly?

CodePudding user response:

You can create a converter based on the Sample Basic Converter in How to write custom converters for JSON serialization and use the extension method from this answer to Remove trailing zeros to solve the problem.

The extension method which removes trailing zeros from the decimal:

public static class ExtensionMethods
{
    public static decimal Normalize(this decimal value) =>
        value / 1.000000000000000000000000000000000m;
}

The json converter utilizing the extension method:

public class DecimalJsonConverter : JsonConverter<decimal>
{
    public override decimal Read(
        ref Utf8JsonReader reader, 
        Type typeToConvert, 
        JsonSerializerOptions options) =>
            reader.GetDecimal().Normalize();

    public override void Write(
        Utf8JsonWriter writer, 
        decimal value, 
        JsonSerializerOptions options) =>         
            writer.WriteNumberValue(value.Normalize());        
}

Register the converter as you mentioned:

builder.Services.Configure<JsonOptions>(opt =>
{
    opt.SerializerOptions.Converters.Add(new DecimalJsonConverter());
}

Online Demo

  • Related