Json.NET序列化浮点/双精度以最小的小数位,即没有多余" 0.0"?小数位、浮点、精度、多余

2023-09-03 12:42:47 作者:匆匆

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

例如,运行此code时:

  JsonConvert.SerializeObject(1.0);
 
为抓外挂,英国19岁CS GO玩家花一年开发AI系统,精确度98 ,查出1万多次作弊

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

 1
 

而是我得到:

 1.0
 

我看了看源$ C ​​$ C,发现这是故意添加提交0319263 (...-固定JsonConvert总是写一个浮点数有小数位......的),其中运行code,它基本上是这样:

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

        返回文本+.0;
    }
 

因此​​,我想知道:

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

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

解决方案   

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:

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

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;