如何将整数反序列化为int而不是long

如何将整数反序列化为int而不是long

本文介绍了如何将整数反序列化为int而不是long?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Json.NET在服务器端反序列化请求.

I'm using Json.NET to deserialize requests on the server-side.

有类似的东西

public object[] Values

我需要输入30.02754.002之类的值,并且它们必须是doubleint的值.

I need to put in values like 30.0, 27, 54.002, and they need to be double's and int's.

Json.NET具有一个称为 FloatParseHandling 的反序列化属性,但是没有像 IntParseHandling 这样的选项.所以问题是如何将整数反序列化为int?

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?

推荐答案

您最好的选择是反序列化为类型化的模型,其中模型表示 Valuesint//等.对于必须为object/object[]的情况(大概是因为类型不是预先已知的,或者它是一组异类项),那么将JSON.NET默认设置为long并不是没有道理的,因为当数组中包含大大小小的值时,这将使混乱最少.除此之外,它无法得知(3L(a long)中的值,当以JSON序列化时,看起来与3(an int)相同).您可以简单地对Values进行后处理并查找long且在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;
    }
}

这篇关于如何将整数反序列化为int而不是long?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 18:54