System.Text.Json默认将double类型的值1.0序列化为int类型的值1
System.Text.Json serializes a value 1.0 of type double to an value 1 of type int by default
我正在升级到 ASP.NET Core 3.1,在切换到 System.Text.Json 后发现浮点值出现奇怪的结果变化。经过调查,我意识到 System.Text.Json 将双精度值转换为整数。例如,考虑一个简单的合约:
public class RowVector
{
[JsonPropertyName("x")]
public double X { get; set; }
[JsonPropertyName("y")]
public double Y { get; set; }
[JsonPropertyName("z")]
public double Z { get; set; }
}
var rowVector = new RowVector { X = 1.0, Y = 213.9, Z = 112.0 };
var serializedData = JsonSerializer.Serialize(rowVector);
Serialized-Data output with System.Text.Json :{"x":1,"y":213.9,"z":112}
这里的 x 和 z 是 int 值,而在 Newtonsoft.Json、
Serialized-Data output with Newtonsoft.Json :{"X":1.0,"Y":213.9,"Z":112.0}
这里 x 和 z 保留为 double。
因此对于 system.text.json,在反序列化时这些值是 int,这会导致我们的处理计算发生变化,知道为什么在 System.Text.Json 中以这种方式实现吗?
你看到的是known portability issue with JSON:
Numbers in JSON are agnostic with regard to their representation within programming languages. While this allows for numbers of arbitrary precision to be serialized, it may lead to portability issues. For example, since no differentiation is made between integer and floating-point values, some implementations may treat 42
, 42.0
, and 4.2E+1
as the same number, while others may not.
另见 here:
For example, a JavaScript-based validator may accept 1.0
as an integer, whereas the Python-based jsonschema does not.
所以无论哪种方式,在 JSON.
中传递数字时都存在可移植性问题
您总是可以 your own converters 来扩展/修改序列化程序的默认行为。
我正在升级到 ASP.NET Core 3.1,在切换到 System.Text.Json 后发现浮点值出现奇怪的结果变化。经过调查,我意识到 System.Text.Json 将双精度值转换为整数。例如,考虑一个简单的合约:
public class RowVector
{
[JsonPropertyName("x")]
public double X { get; set; }
[JsonPropertyName("y")]
public double Y { get; set; }
[JsonPropertyName("z")]
public double Z { get; set; }
}
var rowVector = new RowVector { X = 1.0, Y = 213.9, Z = 112.0 };
var serializedData = JsonSerializer.Serialize(rowVector);
Serialized-Data output with System.Text.Json :{"x":1,"y":213.9,"z":112}
这里的 x 和 z 是 int 值,而在 Newtonsoft.Json、
Serialized-Data output with Newtonsoft.Json :{"X":1.0,"Y":213.9,"Z":112.0}
这里 x 和 z 保留为 double。
因此对于 system.text.json,在反序列化时这些值是 int,这会导致我们的处理计算发生变化,知道为什么在 System.Text.Json 中以这种方式实现吗?
你看到的是known portability issue with JSON:
Numbers in JSON are agnostic with regard to their representation within programming languages. While this allows for numbers of arbitrary precision to be serialized, it may lead to portability issues. For example, since no differentiation is made between integer and floating-point values, some implementations may treat
42
,42.0
, and4.2E+1
as the same number, while others may not.
另见 here:
For example, a JavaScript-based validator may accept
1.0
as an integer, whereas the Python-based jsonschema does not.
所以无论哪种方式,在 JSON.
中传递数字时都存在可移植性问题您总是可以 your own converters 来扩展/修改序列化程序的默认行为。