I am getting the following exception when I am trying to serialize a double that has the value NaN, via JsonConverter
The exception is:
System.ArgumentException: '.NET number values such as positive and negative infinity cannot be written as valid JSON. To make it work when using 'JsonSerializer', consider specifying 'JsonNumberHandling.AllowNamedFloatingPointLiterals' (see https://learn.microsoft.com/dotnet/api/system.text.json.serialization.jsonnumberhandling).'
And yes, due to the project context, I must use JsonConverter, avoiding it is not an option.
Bellow is the code:
// class to serialize
public class Subclass
{
public double NaN { get; set; } = double.NaN;
}
// the convertor
public class SubConvertor : JsonConverter<Subclass>
{
public override Subclass Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
return new Subclass();
}
public override void Write(Utf8JsonWriter writer, Subclass dateTimeValue, JsonSerializerOptions options)
{
writer.WriteStringValue("NaaaN");
writer.WriteNumberValue(dateTimeValue.NaN); //it does work if i would write writer.WriteStringValue(dateTimeValue.NaN.ToString(), but the question is: are there any other more EFFICIENT solutions?
}
}
// Program.cs
var subclass = new Subclass
{
NaN = double.NaN // for a value like 2.3 it works without any problems
};
var serializeOptions = new JsonSerializerOptions
{
NumberHandling = JsonNumberHandling.AllowReadingFromString | JsonNumberHandling.AllowNamedFloatingPointLiterals, //it does not solve the problem as the Excception above suggests
Converters = { new SubConvertor() }
};
var jsonString = JsonSerializer.Serialize(subclass, serializeOptions);
For now I am serializing the double values as strings and after that I am reading and converting them to double. I would like to do this operations more efficient, thus this post.
JsonNumberHandling.AllowNamedFloatingPointLiteralsdoesn't solve your issue, but it does, at least with the code you've given us to reproduce your issue.DoubleConverter- it simply tests for the values that require literals, and branches - github.com/dotnet/runtime/blob/main/src/libraries/… - so maybe your converter could do the same withdouble.IsInfinityetc, writing literals if needed; that doesn't sound inefficient.