Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

ndevenish
Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant