序列化无符号整数(ulong)数组时,Json.NET崩溃

时间:2012-02-20 01:21:59

标签: c# javascript json json.net

尝试序列化ulong数组时出现解析器错误,看起来Json.NET库不检查整数是有符号还是无符号;任何人都知道解决方法吗?或任何其他可以处理unsigned int的.NET Json库?

* 编辑:以下代码; * 序列化很好,但是当它反序列化时会抛出错误;看起来它不能满足unsigned int查看堆栈跟踪;

NewTonsoft.Json.JsonReaderException : {"JSON integer 18446744073709551615 is too large or small for an Int64."}

Value was either too large or too small for an Int64.
   at System.Number.ParseInt64(String value, NumberStyles options, NumberFormatInfo numfmt)
   at System.Convert.ToInt64(String value, IFormatProvider provider)
   at Newtonsoft.Json.JsonTextReader.ParseNumber() in d:\Development\Releases\Json\Working\Src\Newtonsoft.Json\JsonTextReader.cs:line 1360
   class Program
        {
            static void Main(string[] args)
            {
                string output = JsonConvert.SerializeObject(new ulong[] {ulong.MinValue, 20, 21, 22, ulong.MaxValue});
                Console.WriteLine(output);

                ulong[] array = JsonConvert.DeserializeObject<ulong[]>(output);
                Console.WriteLine(array);

                Console.ReadLine();
            }
        }

2 个答案:

答案 0 :(得分:7)

ECMA-262是JSON所基于的标准,在4.3.19节中规定数值是IEEE双精度浮点值,通常在C语言中被视为“双”类型。此编码不够精确,无法表示64位整数的所有可能值。

因此,在JSON中编码64位整数(带符号或其他)可能会导致精度损失,如果它通过任何代码处理符合标准的代码。正如在JSON.net中看到的那样,它也可能会破坏不能正确实现标准的代码,而是假设人们不会尝试做出容易出错的事情。

答案 1 :(得分:6)

你没错,在这种情况下,JSON.Net不会处理大于long.MaxValue的值。

除了修改库的源代码之外,我没有找到任何修改该行为的方法。要解决此问题,您可以将其反序列化为decimal[],然后将其转换为ulong[]