如何使用 System.Text.Json 将浮点数写入(序列化)为具有固定 2 位小数的 JSON?
喜欢
{"Amount": 12.30}
。
不像
{"Amount": 12.3}
或 {"Amount": 12.3001}
或 {"Amount": "12.30"}
。
在 JsonWriterOptions 或 JsonSerializerOptions 中,似乎没有浮点数(或小数或双精度或其他)的小数精度选项。另外编写自己的转换器似乎还不清楚:Utf8JsonWriter writer WriteWhat?
好的找到了,原始转换器似乎可以工作:
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"