JObject.Parse修改浮点值的结尾 [英] JObject.Parse modifies end of floating point values
问题描述
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 double
s 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屋!