Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I deserialize integer number to int, not to long?

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?

like image 311
Igor Shastin Avatar asked Jul 29 '13 07:07

Igor Shastin


1 Answers

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;
    }
}
like image 69
Marc Gravell Avatar answered Nov 14 '22 00:11

Marc Gravell