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

标签 c# parsing windows-phone-8.1 json.net

我试图在 Windows Phone 8.1 上使用 Json.NET 从 json 中获取 BigInteger (System.Numerics),但我得到了 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 而不是大整数。

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

Json.NET 版本:8.0.3

最佳答案

source code JsonTextReader 有这个:

#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 读取它。如果您真的需要将它解释为一个大数字,您可以使用第三方库从字符串中解析它并以这种方式使用它。

关于c# - 使用 JSON.NET JsonTextReader 在 C# 中读取 BigInteger,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37190462/

相关文章:

c# - 如何添加不同的列表框项目 WPF

c# - 概率。关于希伯来语编码

c# - c#中来自c++的unsigned char数组

json - JSONException错误Grails

parsing - 我如何解析 golang 中的非传统日期?

xaml - 如何更改 ContentDialog 过渡?

xaml - Windows Phone 8.1 上使用 MVVM Light 的双向数据绑定(bind)

c# - Prism BindableBase.SetProperty()

ios - 将信息从 Parse 中的用户指针添加到数组 - Swift

c# - Windows Phone 8.1 应用程序在不调试 Async Await 时崩溃