Newtonsoft对大整数失败:如何使用Decimal而不是Int64?

时间:2013-12-13 22:23:36

标签: serialization json.net

我正在使用Newtonsoft二进制文件将流序列化/反序列化为JSON对象:

public static JObject LoadFrom(Stream stream)
{
    return JObject.Load(new JsonTextReader(new StreamReader(stream)));
}

如果流包含一些大整数,如18446744073709552000,则此调用将失败,并显示错误 - JSON integer 18446744073709552000 is too large or small for an Int64。这是因为Newtonsoft将其读取为整数而不是小数。现在我知道我可以通过调整源库和更改序列化中使用的数据类型来解决这个问题。但是,在这种情况下,我只能访问二进制文件而不是源代码 - 是否有针对此的API级解决方法?

谢谢!

1 个答案:

答案 0 :(得分:0)

您是否使用最新版本的Json.Net?这对我使用version 5.0.8

很好
class Program
{
    static void Main(string[] args)
    {
        string json = @"{ test: 18446744073709552000 }";
        MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json));
        JObject jo = LoadFrom(ms);
        JToken token = jo["test"];
        Console.WriteLine("value type = " + token.Type);
        Console.WriteLine("as string = " + token.ToString());
        decimal d = token.ToObject<decimal>();
        Console.WriteLine("as decimal = " + d);
    }

    public static JObject LoadFrom(Stream stream)
    {
        return JObject.Load(new JsonTextReader(new StreamReader(stream)));
    }
}

输出:

value type = Integer
as string = 18446744073709552000
as decimal = 18446744073709552000
相关问题