System.Text.Json 的数字小数精度

问题描述 投票:0回答:1

如何使用 System.Text.Json 将浮点数写入(序列化)为具有固定 2 位小数的 JSON?

喜欢

{"Amount": 12.30}

不像

{"Amount": 12.3}
{"Amount": 12.3001}
{"Amount": "12.30"}

在 JsonWriterOptions 或 JsonSerializerOptions 中,似乎没有浮点数(或小数或双精度或其他)的小数精度选项。另外编写自己的转换器似乎还不清楚:Utf8JsonWriter writer WriteWhat?

c# system.text.json json-serialization
1个回答
0
投票

好的找到了,原始转换器似乎可以工作:

type TwoDecimalsConverter() =
    inherit System.Text.Json.Serialization.JsonConverter<float>()

    override _.Write(writer: System.Text.Json.Utf8JsonWriter, value, serializer) =
        writer.WriteRawValue(value.ToString "0.00")

    override _.Read(reader, typeToConvert, options) =
        failwith "Not implemented"
© www.soinside.com 2019 - 2024. All rights reserved.