skip to Main Content
var jobject = JObject.Parse(str);

If the given json str has the attribute

"seed":11405418255883340000

Error will be thrown: JsonReaderException: JSON integer 11405418255883340000 is too large or small for an Int64

As you’ll notice, 11405418255883340000 is too big for int64. But is a legitimate uint64.

Is this a bug or expected? What’s the easiest workaround?

2

Answers


  1. The easiest is probably to create a DTO that matches the payload you expect and then set the type to ulong of the seed property.

    Here is an example DTO:

    
    public class Seeder {
      public ulong Seed {get;set;}
    }
    

    And here is how you use it, instead of Parse:

    void Main()
    {
        var str = @"{""seed"":11405418255883340000}";
        var ser = new JsonSerializer();
        var jr = new JsonTextReader(new StringReader(str));
        var seed = ser.Deserialize<Seeder>(jr);
        seed.Dump();
    }
    

    This is what LinqPad shows me:

    enter image description here

    If I change the property type back to long I get this exception:

    Error converting value 11405418255883340000 to type ‘System.Int64’. Path ‘seed’, line 1, position 28.

    Note that you don’t have to code a fully specified DTO object. This one works as wel, where we simply don’t have the seed property on our DTO class:

    void Main()
    {
        var str = @"{""seed"":11405418255883340000, ""bar"": 4}";
        var ser = new JsonSerializer();
        var jr = new JsonTextReader(new StringReader(str));
        var seed = ser.Deserialize<Seeder>(jr);
        seed.Dump();
    }
    
    public class Seeder {
      public int Bar {get;set;}
    }
    

    If you are lazy you can drop the JSON payload into an online class generator and/or tooling in your IDE. See for a starting point on that: https://stackoverflow.com/a/21611680

    Login or Signup to reply.
  2. You need System.Numerics so that it can handle BigInteger. The default is to use long not ulong, so it will get an overflow. Then it will try to parse it as a BigInteger.

    The comments in the JSON.Net source code say

    #if HAVE_BIG_INTEGER
            // By using the BigInteger type in a separate method,
            // the runtime can execute the ParseNumber even if 
            // the System.Numerics.BigInteger.Parse method is
            // missing, which happens in some versions of Mono
            [MethodImpl(MethodImplOptions.NoInlining)]
            private static object BigIntegerParse(string number, CultureInfo culture)
            {
                return System.Numerics.BigInteger.Parse(number, culture);
            }
    #endif
    

    So if you can add that library to your project then it should work.

    But your best bet is to just use a proper object model, like the other answer says.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search