You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET中使用JsonSerializer时如何让JSON对象精准保留两位小数(非字符串)

解决JsonSerializer序列化decimal始终保留两位小数的问题

问题场景

从数据库获取decimal类型值1000后,使用JsonSerializer序列化时结果显示为1000.0,但需求是显示为1000.00,且不能以字符串格式输出。目前仅当decimal属性初始化为0.00m时,序列化后才会显示两位小数,相关示例如下:

序列化后的JSON:

{
    "anotherValue": 0.00, 
    "value": 1000.0 // 不允许使用字符串格式的"1000.00"
}

对应的实体类代码:

public class Transaction
{
    public decimal value { get; set; }
    public decimal anotherValue { get; set; } = 0.00m;
}

解决方案:自定义DecimalJsonConverter

通过实现JsonConverter<decimal>来控制decimal类型的序列化逻辑,强制所有decimal值序列化后保留两位小数:

using System.Text.Json;
using System.Text.Json.Serialization;

public class DecimalTwoPlacesConverter : JsonConverter<decimal>
{
    public override decimal Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        // 反序列化时直接读取decimal值,保持原有逻辑
        return reader.GetDecimal();
    }

    public override void Write(Utf8JsonWriter writer, decimal value, JsonSerializerOptions options)
    {
        // 将decimal值四舍五入到两位小数,以数值类型输出而非字符串
        var formattedValue = Math.Round(value, 2);
        writer.WriteNumberValue(formattedValue);
    }
}

使用方式

全局生效

在序列化时将自定义转换器加入JsonSerializerOptions,对所有decimal属性生效:

var transaction = new Transaction
{
    value = 1000m,
    anotherValue = 0m
};

var options = new JsonSerializerOptions
{
    Converters = { new DecimalTwoPlacesConverter() },
    WriteIndented = true // 可选,用于格式化JSON缩进
};

var json = JsonSerializer.Serialize(transaction, options);

此时序列化后的JSON输出为:

{
    "value": 1000.00,
    "anotherValue": 0.00
}

单个属性生效

如果只需要特定属性保留两位小数,可在属性上标记转换器:

public class Transaction
{
    [JsonConverter(typeof(DecimalTwoPlacesConverter))]
    public decimal value { get; set; }
    [JsonConverter(typeof(DecimalTwoPlacesConverter))]
    public decimal anotherValue { get; set; }
}

内容的提问来源于stack exchange,提问作者smomou

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 06:52:41