mbdavid / LiteDB

LiteDB - A .NET NoSQL Document Store in a single data file
http://www.litedb.org
MIT License
8.52k stars 1.24k forks source link

[BUG] NaN and Infinity exception at JsonSerializer.Deserialize #2085

Closed willianwrm closed 2 years ago

willianwrm commented 2 years ago

Version 5.0.11 for .NET Framework 4.5 with C# (NuGet)

Describe the bug Method JsonSerializer.Deserialize throws exceptions while reading NaN or Infinity double values.

Code to Reproduce

// Some invalid value in double
// Other values like 'PositiveInfinity' does not work either
double invalidvalue = double.NaN;

// Creates a simple document
BsonDocument doc = new BsonDocument();
doc["Test"] = invalidvalue;

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

// Convert back to document, exception "Unexpected token `NaN` in position 9" is throw
BsonDocument doc2 = JsonSerializer.Deserialize(json).AsDocument;

Screenshots/Stacktrace

LiteDB.LiteException
  HResult=0x80131500
  Message=Unexpected token `NaN` in position 9.
  Source=LiteDB
  StackTrace:
   at LiteDB.JsonReader.ReadValue(Token token)
   at LiteDB.JsonReader.ReadObject()
   at LiteDB.JsonReader.ReadValue(Token token)
   at LiteDB.JsonSerializer.Deserialize(String json)

JSON value from JsonSerializer.Serialize {"Test":NaN}

Other I did try replacing it to "NaN" (with quotation marks) but then the value is not a double anymore but a string; property BsonValue.AsDouble fails.

AndrewJ-DEV commented 2 years ago

hi line 99 add new case

case "nan": return double.NaN;

LiteDB/Document/Json/JsonReader.cs

kcsombrio commented 2 years ago

Hi @willianwrm, bug fixed. As javascript JSON.stringify() converts NaN to 'null', we just fixed it the same way. So it wouldn't throw the exception anymore and NaN and Infinity values will be serialized to JSON as null.