我有一個使用 EF Core 6 的 ASPNet API 服務器,當我WriteAsJsonAsync用來撰寫十進制屬性時,它變成了:"decimal_property": 0.0000000000000000000000000000. 我不想尾隨零。
我找到了一些自定義轉換的解決方案,但它們都是用寫的,Newtonsoft而不是System.Text.Json像
builder.Services.Configure<JsonOptions>(opt =>
{
opt.SerializerOptions.Converters.Add(new DecimalJsonConverter());
}
一個DecimalJsonConverter可以直接注入的怎么寫WebApplication?
uj5u.com熱心網友回復:
您可以基于如何為 JSON 序列化撰寫自定義轉換器中的示例基本轉換器創建轉換器,并使用此答案中的擴展方法洗掉尾隨零來解決問題。
從十進制中洗掉尾隨零的擴展方法:
public static class ExtensionMethods
{
public static decimal Normalize(this decimal value) =>
value / 1.000000000000000000000000000000000m;
}
使用擴展方法的 json 轉換器:
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());
}
按照您的說明注冊轉換器:
builder.Services.Configure<JsonOptions>(opt =>
{
opt.SerializerOptions.Converters.Add(new DecimalJsonConverter());
}
在線演示
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/394297.html
