gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 12:23:22 26 4
gpt4 key购买 nike

我试图在 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com