Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Getting a parser error when trying to serialize a ulong array, looks like the Json.NET library isnt checking if the integer is signed or unsigned; any one know of a workaround for this? or any other .NET Json library that can handle unsigned int's?

*EDIT: code below; * It serializes fine, but when its deserializing it throws an error; Looks like it doesnt cater for the unsigned int from looking at 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();
            }
        }
like image 605
Ricky Gummadi Avatar asked Feb 20 '12 01:02

Ricky Gummadi


People also ask

Is Newtonsoft deprecated?

Despite being deprecated by Microsoft in . NET Core 3.0, the wildly popular Newtonsoft. Json JSON serializer still rules the roost in the NuGet package manager system for . NET developers.

How to serialize to JSON?

NET objects as JSON (serialize) To write JSON to a string or to a file, call the JsonSerializer. Serialize method.

How to deserialize the JSON string in c#?

We can implement JSON Serialization/Deserialization in the following three ways: Using JavaScriptSerializer class. Using DataContractJsonSerializer class. Using JSON.NET library.


1 Answers

ECMA-262, the standard on which JSON is based, specifies in section 4.3.19 that number values are IEEE double-precision floating point values, commonly seen as the "double" type in C-like languages. This encoding is not sufficiently precise to represent all possible values of 64 bit integers.

Therefore, encoding 64 bit integers (signed or otherwise) in JSON may lead to a loss in precision if it passes through any code which processes it in keeping with the standard. As seen in JSON.net, it might also break code which does not correctly implement the standard, but rather assumes that people won't try to do failure-prone things.

like image 71
Benjamin Saunders Avatar answered Nov 10 '22 20:11

Benjamin Saunders