问题
I have a JSON string:
{"PaymentVoucherNumber":15,"PaymentVoucherDate":"2019-09-10T00:00:00","pvExpiryDate":"2019-09-22T00:00:00","Amount":35.000,"ReceiptNumber":0}
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; }
}
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);
Please advice...
回答1:
Your problem is that, in your data model, you are using double
and not decimal
for Amount
:
[JsonProperty("Amount")]
public double Amount { get; set; }
You need to change that to decimal
:
[JsonProperty("Amount")]
public decimal Amount { get; set; }
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:
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. ...
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.
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.
Sample fiddle.
来源:https://stackoverflow.com/questions/57867163/jsonconvert-populateobject-is-not-handling-the-decimal-type-data-properly