Skip to content

Commit

Permalink
litedb-org#2085 - fix NaN and Infinity exception at JsonSerializer.De…
Browse files Browse the repository at this point in the history
…serialize
  • Loading branch information
kcsombrio committed Dec 30, 2021
1 parent 7bba069 commit be622b8
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
19 changes: 19 additions & 0 deletions LiteDB.Tests/Document/Json_Tests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -75,5 +75,24 @@ public void Json_Number_Deserialize_Test()
JsonSerializer.Deserialize(positiveDouble.ToString("F1", CultureInfo.InvariantCulture)).Should().Be(positiveDouble);
JsonSerializer.Deserialize(negativeDouble.ToString("F1", CultureInfo.InvariantCulture)).Should().Be(negativeDouble);
}

[Fact]
public void Json_DoubleNaN_Tests()
{
BsonDocument doc = new BsonDocument();
doc["doubleNaN"] = double.NaN;
doc["doubleNegativeInfinity"] = double.NegativeInfinity;
doc["doublePositiveInfinity"] = double.PositiveInfinity;

// Convert to JSON
string json = JsonSerializer.Serialize(doc);

var bson = JsonSerializer.Deserialize(json);

// JSON standard converts NaN and Infinities to null, so deserialized values should not be double.NaN nor double.*Infinity
Assert.False(double.IsNaN(bson["doubleNaN"].AsDouble));
Assert.False(double.IsNegativeInfinity(bson["doubleNegativeInfinity"].AsDouble));
Assert.False(double.IsPositiveInfinity(bson["doublePositiveInfinity"].AsDouble));
}
}
}
12 changes: 11 additions & 1 deletion LiteDB/Document/Json/JsonWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,17 @@ private void WriteValue(BsonValue value)
break;

case BsonType.Double:
_writer.Write(value.AsDouble.ToString("0.0########", _numberFormat));
var d = value.AsDouble;

if (double.IsNaN(d) || double.IsNegativeInfinity(d) || double.IsPositiveInfinity(d))
{
_writer.Write("null");
}
else
{
_writer.Write(value.AsDouble.ToString("0.0########", _numberFormat));
}

break;

case BsonType.Binary:
Expand Down

0 comments on commit be622b8

Please sign in to comment.