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

标签 c# javascript json json.net

尝试序列化 ulong 数组时出现解析器错误,看起来 Json.NET 库没有检查整数是有符号还是无符号;有人知道解决方法吗?或任何其他可以处理无符号整数的 .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();
            }
        }

最佳答案

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

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

关于c# - 序列化无符号整数 (ulong) 数组时 Json.NET 崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9355091/

相关文章:

javascript - 如何获取 Facebook AR 手部追踪器的 x 位置?

javascript - 如何替换 jQuery DOM 元素中的字符串

Javascript `await` "SyntaxError: Unexpted identifier"即使我在 `async` 函数中等待

java - 使用数据库中的数据创建 JSON 数组

javascript - 从数组对象获取值

javascript - 在第一层创建 JSON 属性键链接

c# - 将父控件的属性传递给子控件

c# - HttpCacheability.NoCache 和 Response.CacheControl = "no-cache"之间有什么不同?

c# - Convert.ToInt16 或 32 或 64 与 Int.Parse 之间有什么区别?

c# - ASP.Net 无法成功登录/注册(可以在本地运行,但不能在 Azure 上运行)