I have following JSON object returned by vatlayer api
{
"success":true,
"rates":{
"AT":{
"country_name":"Austria",
"standard_rate":20,
"reduced_rates":{
"foodstuffs":10,
"books":10,
"pharmaceuticals":10,
"passenger transport":10,
"newspapers":10,
"admission to cultural events":10,
"hotels":10,
"admission to entertainment events":10
}
},
"BE":{
"country_name":"Belgium",
"standard_rate":21,
"reduced_rates":{
"restaurants":12,
"foodstuffs":6,
"books":6,
"water":6,
"pharmaceuticals":6,
"medical":6,
"newspapers":6,
"hotels":6,
"admission to cultural events":6,
"admission to entertainment events":6
}
},
"BG":{
"country_name":"Bulgaria",
"standard_rate":20,
"reduced_rates":{
"hotels":9
}
}
...more obejcts
...more objects
...more objects
}
I want to read data in following class
public class Country{
public string ShortCode{get;set;}// AT, BE, etc are examples of shortcode
public string Country_Name{get;set;}// Austria, Belgium etc
public decimal Standar_Rate{get;set;}// 20 and 21 respectively
}
The problem is that web service is not sending data as an array of JSON objects. Rather, its sending a single object where each country short code is the key in JSON. How do I deserialize this object to List
or Array
of Country
objects. I am open to using any JSON converter
Just model the response like this:
public class Response
{
public bool Success { get; set; }
public Dictionary<string, Country> Rates { get; set; }
}
Then:
var response = JsonConvert.DeserializeObject<Response>(json);
var allCountries = response.Rates.Values.ToList();
Note that that won't give you the ShortCode
, which is in the dictionary key. You could get that using:
// Assuming the names have been fixed to be idiomatic...
var allCountries = response.Rates.Select(pair =>
new Country {
CountryName = pair.Value.CountryName,
StandardRate = pair.Value.StandardRate,
ShortCode = pair.Key
})
.ToList();
See more on this question at Stackoverflow