JsonConvert.PopulateObject()未正确处理十进制类型数据 [英] JsonConvert.PopulateObject() is not handling the decimal type data properly
问题描述
我有一个JSON字符串:
I have a JSON string:
{"PaymentVoucherNumber":15,"PaymentVoucherDate":"2019-09-10T00:00:00","pvExpiryDate":"2019-09-22T00:00:00","Amount":35.000,"ReceiptNumber":0}
在此json中,Amount
是一个双精度值.
In this json the Amount
is a double value.
public partial class VoucherList
{
[JsonProperty("PaymentVoucherNumber")]
public long PaymentVoucherNumber { get; set; }
[JsonProperty("PaymentVoucherDate")]
public string PaymentVoucherDate { get; set; }
[JsonProperty("pvExpiryDate")]
public string PvExpiryDate { get; set; }
[JsonProperty("Amount")]
public double Amount { get; set; }
[JsonProperty("ReceiptNumber")]
public long ReceiptNumber { get; set; }
}
我使用了JsonConvert.PopulateObject().但是结果是,金额字段将以小数部分删除.即仅35
I have used JsonConvert.PopulateObject(). But in the result, the amount field is coming as decimal part removed.ie just 35
VoucherList pv=new VoucherList();
JsonConvert.PopulateObject(json,pv);
请咨询...
推荐答案
您的问题是,在您的数据模型中,对于Amount
,您使用的是double
而不是decimal
:
Your problem is that, in your data model, you are using double
and not decimal
for Amount
:
[JsonProperty("Amount")]
public double Amount { get; set; }
您需要将其更改为decimal
:
[JsonProperty("Amount")]
public decimal Amount { get; set; }
当您这样做时,JSON中的小数位数将被保存在decimal
结构中.这是可能的,因为如 docs :
When you do, the number of decimal digits in the JSON will be remembered in the decimal
struct. This is possible because, as explained in the docs:
十进制数是一个浮点值,它由一个符号,一个数值(其中值中的每个数字都介于0到9之间)和一个比例因子(表示将整数分隔开的浮点小数的位置)组成数值的小数部分. ...
A decimal number is a floating-point value that consists of a sign, a numeric value where each digit in the value ranges from 0 to 9, and a scaling factor that indicates the position of a floating decimal point that separates the integral and fractional parts of the numeric value. ...
比例因子还保留十进制数中的所有尾随零.尾随零不会影响算术或比较操作中小数的值.但是,如果应用了适当的格式字符串,则ToString方法可能会显示尾随零.
The scaling factor also preserves any trailing zeros in a Decimal number. Trailing zeros do not affect the value of a Decimal number in arithmetic or comparison operations. However, trailing zeros might be revealed by the ToString method if an appropriate format string is applied.
对于 double
是纯IEEE 754二进制浮点表示形式,因此不能区分35
,35.0
或35.0000
.结果,当您在填充后检查pv.Amount
时,将显示35
作为35.0
JSON值.
No such capability is present for double
which is a purely IEEE 754 binary floating-point representation and thus cannot distinguish between 35
, 35.0
or 35.0000
. As a result, when you inspect pv.Amount
after population, 35
is shown for the 35.0
JSON value.
示例小提琴.
这篇关于JsonConvert.PopulateObject()未正确处理十进制类型数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!