问题
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