反序列化时缺少JSON.Net构造函数参数

Bri*_*chl 3 .net json json.net deserialization

我有一个简单的对象,我正在通过JSON往返.它序列化很好,但我反序列化其中一个值设置为默认值(在这种情况下为0).这是为什么?

这是我的目标:

public class CurrencyExchangeRate
{
    public string CurrencyCode { get; private set; }
    public decimal Rate { get; private set; }

    public CurrencyExchangeRate(string currencyCode, decimal exchangeRate)
    {
        this.CurrencyCode = currencyCode;
        this.Rate = exchangeRate;
    }
}
Run Code Online (Sandbox Code Playgroud)

这序列化为JSON {"CurrencyCode":"USD", "Rate": 1.10231}.但是当我反序列化时,Rate字段始终设置为0.该CurrencyCode字段已正确设置,因此显然反序列化不会完全失败,只有一个字段失败.

Bri*_*chl 6

构造函数参数名称错误.

因为没有无参数构造函数,JSON.net被迫使用带参数的构造函数并为这些参数提供值.它尝试通过比较它们的名称来匹配JSON字符串中的字段和构造函数的参数.这适用于货币代码,因为CurrencyCode它足够接近currencyCode.但是JSON字段名称Rate与构造函数参数的区别太大exchangeRate,因此JSON.net无法弄清楚它们是同一个东西.因此,0m在这种情况下,它会传递该类型的默认值.将构造函数参数名称更改为类似rate将解决问题.

public class CurrencyExchangeRate
{
    public string CurrencyCode { get; private set; }
    public decimal Rate { get; private set; }

    //NOTE changed parameter name!
    public CurrencyExchangeRate(string currencyCode, decimal rate)
    {
        this.CurrencyCode = currencyCode;
        this.Rate = rate;
    }
}
Run Code Online (Sandbox Code Playgroud)