I'm using Json.NET to deserialize requests on the server-side.
There is something like
public object[] Values
I need to put in values like 30.0
, 27
, 54.002
, and they need to be double
's and int
's.
Json.NET has a deserialization property called FloatParseHandling, but there is no option like IntParseHandling. So the question is how can I deserialize integers to int
?
Your best bet is to deserialize into a typed model where the model expresses that Values
is an int
/ int[]
/ etc. In the case of something that has to be object
/ object[]
(presumably because the type is not well-known in advance, or it is an array of heterogeneous items), then it is not unreasonable for JSON.NET to default to long
, since that will cause the least confusion when there are a mixture of big and small values in the array. Besides which, it has no way of knowing what the value was on the way in (3L
(a long
), when serialized in JSON, looks identical to 3
(an int
)). You could simply post-process Values
and look for any that are long
and in the int
range:
for(int i = 0 ; i < Values.Length ; i++)
{
if(Values[i] is long)
{
long l = (long)Values[i];
if(l >= int.MinValue && l <= int.MaxValue) Values[i] = (int)l;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With