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

谁说我不能喝 提交于 2019-12-23 07:49:47

问题


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?


回答1:


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;
    }
}


来源:https://stackoverflow.com/questions/17918686/how-can-i-deserialize-integer-number-to-int-not-to-long

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!