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;
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.
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.
Worse, attempting to reparse the output from SimpleJSON throws a serializationException;
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 functionobject CoerceInfiniteOrNaN(object value)
. This allows the value being serialized to be coerced to a different (valid JSON) form - as an example, an extra strategyInfinityAsStringJsonSerializerStrategy
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.