JObject.Parse 修改浮点值的结尾 [英] JObject.Parse modifies end of floating point values

查看:22
本文介绍了JObject.Parse 修改浮点值的结尾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var clientString = "{"max":1214.704958677686}";

JObject o = JObject.Parse(clientString);

var jsonString = o.ToString();

<小时>

jsonString 的内容:


contents of jsonString:

{
  "max": 1214.7049586776859
}

这既用于可视化对象,也用于执行 ToString().请注意,686 已神秘地扩展到 6859(添加了精度).这对我们来说是个问题,因为数字不完全相同,而且后面的 json 上的哈希函数不匹配.

this is both in visualizing the object and in doing ToString(). Note that the 686 has mysteriously been expanded to 6859 (precision added). This is a problem for us because the numbers are not exactly the same, and a hash function over the json later does not match.

推荐答案

@Ilija Dimov 是正确的——JSON.NET 默认将 JSON 浮点数解析为 double.如果您仍想使用 JObject 而不是创建完整的 POCO 进行反序列化,则可以使用 JsonTextReader 并设置 FloatParseHandling 选项:

@Ilija Dimov is correct--JSON.NET parses JSON floats as doubles by default. If you still want to use JObject instead of creating a full blown POCO for deserialization, you can use a JsonTextReader and set the FloatParseHandling option:

var reader = new JsonTextReader(new StringReader(clientString));
reader.FloatParseHandling = FloatParseHandling.Decimal;

JObject obj = JObject.Load(reader);

Console.WriteLine(obj["max"].Value<decimal>()); // 1214.704958677686

这篇关于JObject.Parse 修改浮点值的结尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆