JSON.Net constructor parameter missing when deserializing

生来就可爱ヽ(ⅴ<●) 提交于 2020-01-13 19:06:59

问题


I have a simple object that I'm roundtripping through JSON. It serializes just fine, but I deserialize it one of the values is set to the default value (0, in this particular case). Why is that?

Here's my object:

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;
    }
}

This serializes to JSON as something like {"CurrencyCode":"USD", "Rate": 1.10231}. But when I deserialize it the Rate field is always set to 0. The CurrencyCode field is correctly set, so clearly deserialization is not failing entirely, just the one field is failing.


回答1:


The constructor parameters are named wrong.

Because there is no parameterless constructor, JSON.net is forced to use the constructor with parameters and provide values for those parameters. It tries to match up the fields from the JSON string with the parameters to your constructor by comparing their names. This works for the currency code because CurrencyCode is close enough to currencyCode. But the JSON field name Rate is too different from the constructor parameter exchangeRate, so JSON.net can't figure out that they're the same thing. Thus it passes the default value for that type, 0m in this case. Changing the constructor parameter name to be something like rate will fix the problem.

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;
    }
}


来源:https://stackoverflow.com/questions/21733792/json-net-constructor-parameter-missing-when-deserializing

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