Home > Blockchain >  How correctly to create model for json deserialization?
How correctly to create model for json deserialization?

Time:01-16

How to deserialize a JSON into C# objects?

This is my JSON:

{
    "date": "2020-07-02 10:39:00 00",
    "base": "USD",
    "rates": {
        "FJD": 2.1692,
        "MXN": 22.602,
      [...]
    }
}

Root model

public class BaseCurrencyModel
{
    public DateTime Date { get; set; }
    public string Base { get; set; }
    public IEnumerable<RatesModel> Rates { get; set; }
}

Object for array values:

public class RatesModel
{
    public string currencyCode { get; set; }
    public string rate { get; set; }
}

When I use

public Dictionary<string, string> Rates 

into root model everything it's working fine. If I use

IEnumerable<RatesModel> Rates

I get the error

Cannot deserialize the current JSON object into type 'System.Collections.Generic.IEnumerable`1[CurrencyConverter.Models.RatesModel]'because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array

CodePudding user response:

json rates are not array it is a dictionary

public class BaseCurrencyModel
{
    public DateTime Date { get; set; }

    public string Base { get; set; }

    public Dictionary<string,double> Rates { get; set; }
}

or you can convert it to List

    var ratesParsed= JObject.Parse(json);
    BaseCurrencyModel rates = new BaseCurrencyModel
    {
        Date = ratesParsed["date"].ToObject<DateTime>(),
        Base = (string)ratesParsed["base"],
        Rates = ((JObject)ratesParsed["rates"]).Properties().Select(x => 
                   new RatesModel { currencyCode = x.Name, 
                   rate = Convert.ToDouble(x.Value) }
                ).ToList()
    };

class

public class BaseCurrencyModel
{
    public DateTime Date { get; set; }

    public string Base { get; set; }

    public List<Rate> Rates { get; set; }
}

output (in a json format)

{
  "Date": "2020-07-02T08:09:00-02:30",
  "Base": "USD",
  "Rates": [
    {
      "currencyCode": "FJD",
      "rate": 2.1692
    },
    {
      "currencyCode": "MXN",
      "rate": 22.602
    }
  ]
}
  •  Tags:  
  • Related