facebook-csharp-sdk / simple-json

JSON library for .NET 2.0+/SL4+/WP7/WindowsStore with optional support for dynamic and DataContract
MIT License
379 stars 143 forks source link

Put in a strategy to determine how NaN/Infinity is handled #69

Open ndevenish opened 9 years ago

ndevenish commented 9 years ago

Currently encoding from a double or float with value NaN or +/- Inf results in invalid JSON - any doubles are simply encoded as String(value) which leads to e.g.

var dData = new Dictionary<string, object>();
dData["infinity"] = double.PositiveInfinity;
Debug.WriteLine(SimpleJson.SerializeObject(dData));
// Output: {"infinity":Infinity}

Worse, attempting to reparse the output from SimpleJSON throws a serializationException;

SimpleJson.DeserializeObject(SimpleJson.SerializeObject(dData));
// -> SerializationException : Invalid JSON string

Clearly, this does not appear to be a problem for too many people; otherwise it would have been altered already, and I've assumed that making these automatically into strings would be unacceptable - certainly it would risk breaking existing behaviour.

This pull request implements an additional feature to the SerializerStrategy, that gives the user the option to define how these values are handled, the function object CoerceInfiniteOrNaN(object value). This allows the value being serialized to be coerced to a different (valid JSON) form - as an example, an extra strategy InfinityAsStringJsonSerializerStrategy is included which simply ensures the value is encoded as a JSON-string in the NaN/Infinity cases. I can imagine depending on the target application, the user might want to e.g. cap to a large value, change to zero, or some other behavior.