[英]Deserializing the Json object to .NET object
我有以下由vatlayer API返回的JSON对象
{
"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
}
我想在下课时阅读数据
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
}
问题在于,Web服务未将数据作为JSON对象数组发送。 相反,它发送一个对象,每个国家/地区的短代码是JSON中的键。 如何将该对象反序列化为“ List
或“ Country
Array
”对象。 我愿意使用任何JSON转换器
像这样对响应建模:
public class Response
{
public bool Success { get; set; }
public Dictionary<string, Country> Rates { get; set; }
}
然后:
var response = JsonConvert.DeserializeObject<Response>(json);
var allCountries = response.Rates.Values.ToList();
请注意,这不会给您字典关键字中的ShortCode
。 您可以使用以下方法得到它:
// 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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.