Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.Text.Json: Handling Infinity values

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?

like image 567
Jeremy Avatar asked Aug 25 '26 14:08

Jeremy


2 Answers

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
-∞
∞
like image 156
tymtam Avatar answered Aug 27 '26 03:08

tymtam


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());            
    }
}
like image 37
Jeremy Avatar answered Aug 27 '26 05:08

Jeremy