I have some .NET
code that deserializes JSON
objects created by a webservice
running a dynamic language. Because the source is dynamic, it sometimes serializes integral values in float format (e. g. 2 gets serialized to "2.0").
With Json.NET 4.0.4
, this worked seamlessly (seems like rounding was applied when deserializing). With the upgrade to Json.NET 4.5
, though, deserializing 2.0 now throws a FormatException
. Here's the code:
// works as expected in both versions
var s = "2";
Console.WriteLine(JsonConvert.DeserializeObject<int>(s));
// throws FormatException in 4.5 only
var s = "2.0";
Console.WriteLine(JsonConvert.DeserializeObject<int>(s));
// throws FormatException in 4.5, rounds to 3 in 4.0.4
var s = "2.6";
Console.WriteLine(JsonConvert.DeserializeObject<int>(s));
Is there any easy way to restore the original behavior? The ideal behavior would be to deserialize only numbers with integral values, but in any format (e. g. 2.0, 1e10, but not 2.5), but I'd settle for the 4.0.4 behavior.