Json.NET序列化浮点/双精度以最小的小数位,即没有多余" 0.0"? [英] Json.NET serializing float/double with minimal decimal places, i.e. no redundant ".0"?

查看:1286
本文介绍了Json.NET序列化浮点/双精度以最小的小数位,即没有多余" 0.0"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在序列化和双精度浮点数,Json.NET总是在结尾加上.0如果数字不包含任何小数部分。我在想,如果有一个简单的方法来绕过这一点,导致了更紧凑的再presentation?额外的时间和零加起来序列包含许多数字对象时。

例如,运行此code时:

  JsonConvert.SerializeObject(1.0);
 

我希望(和希望)这样的结果:

 1
 

而是我得到:

 1.0
 

我看了看源$ C ​​$ C,发现这是故意添加提交<一href="https://github.com/JamesNK/Newtonsoft.Json/commit/0319263756212f4a1875cda6534b9b8e1fb53188">0319263 (...-固定JsonConvert总是写一个浮点数有小数位......的),其中运行code,它基本上是这样:

 私有静态字符串EnsureDecimalPlace(double值,文本字符串)
    {
        如果(double.IsNaN(值)|| double.IsInfinity(值)||
            text.IndexOf('。')!=  -  1 || text.IndexOf(E)!= -1 ||
            text.IndexOf(E)!= -1)
        {
            返回文本;
        }

        返回文本+.0;
    }
 

因此​​,我想知道:

  1. 这可能已经为这种变化的原因是什么?该 JSON规范似乎并不需要它。

  2. 有没有一种简单的方法来绕过它?

解决方案
  

1。什么可能是对这种变化的原因是什么?

的规格不要求,但它也不会不接受它。

我的猜测是,它可以更好地类型检查Json.NET(如果他们有它的地方),或者这是一个刚刚在案的东西,可以让整数和浮点类型之间的差异。

  

2。有没有一种简单的方法来绕过它?

不是那么容易,但如果你真的想要的话,你可以更改后重新编译您自己的版本Json.NET的 EnsureDecimalPlace()简单地返回文本;

When serializing floats and doubles, Json.NET always adds ".0" at the end if the number doesn't contain any fractional part. I was wondering if there was an easy way to bypass this, to result in a more compact representation? The extra periods and zeroes add up when serializing an object containing many numbers.

For example, when running this code:

JsonConvert.SerializeObject(1.0);

I would expect (and want) this result:

"1"

But instead I get:

"1.0"

I looked at the source code and noticed that it was purposely added in commit 0319263 ("...-Fixed JsonConvert to always write a floating point number with a decimal place...") where it runs code that looks basically like:

    private static string EnsureDecimalPlace(double value, string text)
    {
        if (double.IsNaN(value) || double.IsInfinity(value) ||
            text.IndexOf('.') != -1 || text.IndexOf('E') != -1 ||
            text.IndexOf('e') != -1)
        {
            return text;
        }

        return text + ".0";
    }

Consequently, I am wondering:

  1. What may have been the reason for that change? The JSON specification does not seem to require it.

  2. Is there an easy way to bypass it?

解决方案

1. What may have been the reason for that change?

The specs do not require it, but it also does not disallow it.

My guess is that it allows for better type checking for Json.NET (if they have it somewhere) or it's a "just-in-case" thing that allows differentiation between integer and floating point types.

2. Is there an easy way to bypass it?

Not that easy, but if you really want it, you can recompile your own version of Json.NET after changing EnsureDecimalPlace() to simply return text;

这篇关于Json.NET序列化浮点/双精度以最小的小数位,即没有多余&QUOT; 0.0&QUOT;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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