Closed fededim closed 4 years ago
NaN
and other floating point constants (infinity, negative infinity) are not valid for (de)serialization using System.Text.Json In ASP.NET 3.1, hence the error you are seeing.
For .NET 5.0, we've added a "number handling" feature that allows you to opt in to read and write these floating point constants - https://github.com/dotnet/runtime/pull/39363. This feature will be available in .NET preview 8, but will not be ported to 3.1
The work around for 3.1 is to add a custom converter for the double
type to a JsonSerializerOptions instance, or on each property that requires this handling.
public class DoubleConverter : JsonConverter<double>
{
public override double Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (reader.TokenType == JsonTokenType.String && reader.GetString() == "NaN")
{
return double.NaN;
}
return reader.GetDouble(); // JsonException thrown if reader.TokenType != JsonTokenType.Number
}
public override void Write(Utf8JsonWriter writer, double value, JsonSerializerOptions options)
{
if (double.IsNaN(value))
{
writer.WriteStringValue("NaN");
}
else
{
writer.WriteNumberValue(value);
}
}
}
I am working on a project based asp.net core 3.1, EF Code First and NTSTopologySuite. I do have Point properties in my entites to specify geographic location, however when I try to return the entity from a standard WebApi2 controller the serialization fails with the following error:
The problem is that the Point class has some properties with NaN values. I could skip the serialization of Point properties with JsonIgnore attribute, but that's not what I need (I need to have the geographic location). Any plan to support NaN values in JSON serialization of Double ? As a matter of fact, double datatype has also this possible value and I do not see why it can't be serialized.