JsonConvert.PopulateObject() is not handling the decimal type data properly

谁说我不能喝 提交于 2020-04-30 08:10:47

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!