From what I can tell, this is the appropriate way to handle double "Infinity" values when using NewtonsoftJson, to avoid those values when serializing.
x.SerializerSettings.FloatFormatHandling = FloatFormatHandling.DefaultValue;
What is the corresponding way to do this when using System.Text.Json?
Without a custom converter you cannot instruct System.Text.Json to write a 0, but - for the record - NaN and the infinities can be handled with JsonNumberHandling.AllowNamedFloatingPointLiterals.
From JsonNumberHandling Enum:
The "NaN", "Infinity", and "-Infinity" String tokens can be read as floating-point constants, and the Single and Double values for these constants will be written as their corresponding JSON string representations.
using System.Text.Json;
var options = new JsonSerializerOptions {
NumberHandling = System.Text.Json.Serialization.JsonNumberHandling.AllowNamedFloatingPointLiterals
};
Console.WriteLine(JsonSerializer.Serialize(Double.NaN, options));
Console.WriteLine(JsonSerializer.Serialize(Double.NegativeInfinity, options));
Console.WriteLine(JsonSerializer.Serialize(Double.PositiveInfinity, options));
Console.WriteLine(JsonSerializer.Deserialize<double>("\"NaN\"", options));
Console.WriteLine(JsonSerializer.Deserialize<double>("\"-Infinity\"", options));
Console.WriteLine(JsonSerializer.Deserialize<double>("\"Infinity\"", options));
prints
"NaN"
"-Infinity"
"Infinity"
NaN
-∞
∞
I ended up using a custom converter.
In startup.cs
.AddJsonOptions(options =>
options.JsonSerializerOptions.Converters.Add(new DoubleInfinityConverter())
);
The converter
internal class DoubleInfinityConverter : JsonConverter<double>
{
public override double Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) => reader.GetDouble();
public override void Write(Utf8JsonWriter writer, double value, JsonSerializerOptions options)
{
if (double.IsNaN(value) || double.IsInfinity(value))
{
writer.WriteStringValue(default(double).ToString());
return;
}
writer.WriteStringValue(value.ToString());
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With