Json.NET crashes while serializing array unsigned integer (ulong)

Getting a parser error while trying to serialize an ulong array looks like the Json.NET library does not check if an integer is signed or not; Does anyone know of a workaround for this? or any other .NET Json library that can handle unsigned int?

* EDIT: code below; * It serializes perfectly, but when its deserialization causes an error; It doesn't seem to be serving an unsigned int from viewing the stack trace;

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(); } } 
+6
source share
2 answers

You are correct, JSON.Net does not process values โ€‹โ€‹exceeding long.MaxValue in this case.

I did not find a way to change this behavior, except for changing the source code of the library. As a workaround, you can deserialize it as decimal[] and then convert it to ulong[] .

+6
source

ECMA-262 , the standard on which JSON is based, indicates in section 4.3.19 that numeric values โ€‹โ€‹are IEEE double-precision floating-point values, which are generally considered to be a "double" type in C-type languages. This encoding is not accurate enough to represent all possible values โ€‹โ€‹of 64-bit integers.

Therefore, encoding 64-bit integers (signed or otherwise) in JSON can lead to loss of precision if it passes through any code that processes it in accordance with the standard. As can be seen from JSON.net, it can also break code that incorrectly implements the standard, but assumes that people will not try to do disastrous things.

+7
source

Source: https://habr.com/ru/post/908861/


All Articles