JSON不区分float
和int
,它只有Number的概念,所以一般来说,你应该避免依赖于特定的数字格式.
如果你目前不能修复使用JSON的应用程序,你可以使用custom converter,它将使用特定的number format.例如:
class FloatConverter : JsonConverter<float>
{
public override float Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) =>
throw new NotImplementedException();
public override void Write(Utf8JsonWriter writer, float value, JsonSerializerOptions options)
{
// at least one decimal place, add reasonable amount of places with #
writer.WriteRawValue(value.ToString("0.0########", CultureInfo.InvariantCulture));
}
}
和用法:
var serialize = JsonSerializer.Serialize(new float[] { 1, 1.1f, 4.5555f }, new JsonSerializerOptions
{
Converters = { new FloatConverter() }
});
Console.WriteLine(serialize); // prints "[1.0,1.1,4.5555]"