使用 JSON.NET JsonTextReader 在 C# 中读取 BigInteger

Reading BigInteger in C# with JSON.NET JsonTextReader

我正在尝试在 Windows 上使用 Json.NET 从 json 获取 BigInteger (System.Numerics) Phone 8.1,但我得到一个 Newtonsoft.Json.JsonReaderException.

为了重现错误,我将代码缩减为以下片段:

    string json = @"{
       'BFN': 123456789012345678901234
    }";

    JsonTextReader jTR = new JsonTextReader(new StringReader(json));

    while (jTR.Read())
    {
        if (jTR.Value != null)
        {
            System.Diagnostics.Debug.WriteLine("Token: {0}, Value: {1}", jTR.TokenType, jTR.Value);
        }
        else
        {
            System.Diagnostics.Debug.WriteLine("Token: {0}", jTR.TokenType);
        }
    }

运行 此代码在 jTR.Read():

出现以下错误

An exception of type 'Newtonsoft.Json.JsonReaderException' occurred in Newtonsoft.Json.DLL but was not handled in user code

Additional information: JSON integer 123456789012345678901234 is too large or small for an Int64.

据我从源代码中得知,此异常是在 JsonTextReader 的第 2010 行抛出的,但我无法理解它尝试的原因使用 Int64 而不是 BigInteger。

非常感谢任何帮助或信息。

Json.NET版本:8.0.3

JsonTextReadersource code 有这个:

#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)

    string number = _stringReference.ToString();

    if (number.Length > MaximumJavascriptIntegerCharacterLength)
    {
        throw JsonReaderException.Create(this, "JSON integer {0} is too large to parse.".FormatWith(CultureInfo.InvariantCulture, _stringReference.ToString()));
    }

    numberValue = BigIntegerParse(number, CultureInfo.InvariantCulture);
    numberType = JsonToken.Integer;

#else

    throw JsonReaderException.Create(this, "JSON integer {0} is too large or small for an Int64.".FormatWith(CultureInfo.InvariantCulture, _stringReference.ToString()));

#endif

注意里面有条件编译指令。简而言之,如果您使用的是 Json.Net 库的便携版本(我假设您使用的是 Windows Phone),则 BigInteger 不受支持。

如果您可以控制 JSON 的格式,请尝试引用较大的数字,使其成为字符串而不是纯整数。这将允许 Json.Net 阅读它。如果你真的需要将它解释为一个大数字,你可以使用第三方库从字符串中解析它并以这种方式使用它。