3

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
  • I'm curious what the downvote was for? Since someone just went through and downvoted two other questions that I answered myself, I'll just point out that that is actually a fully supported feature of StackOverflow. There's even a checkbox for "answer your own question - share your knowledge Q&A style" on the "Ask a question" form. Commented Jun 4, 2014 at 19:26

1 Answer 1

6

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;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.