C# 将Json对象反序列化为.NET对象
我有以下由vatlayer api返回的JSON对象C# 将Json对象反序列化为.NET对象,c#,.net,json,deserialization,C#,.net,Json,Deserialization,我有以下由vatlayer api返回的JSON对象 { "success":true, "rates":{ "AT":{ "country_name":"Austria", "standard_rate":20, "reduced_rates":{ "foodstuffs":10, "books":10, "pharmaceuticals":10, "passenger tran
{
"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中的关键。如何将此对象反序列化为
国家
对象的列表
或数组
。我愿意使用任何JSON转换器只需对响应进行如下建模:
public class Response
{
public bool Success { get; set; }
public Dictionary<string, Country> Rates { get; set; }
}
只需对响应进行如下建模:
public class Response
{
public bool Success { get; set; }
public Dictionary<string, Country> Rates { get; set; }
}
将其反序列化到
词典
,然后该词典的值
将为您提供收藏。将其反序列化到词典
,然后该词典的值
将为您提供收藏。我想,谢谢@Jon Skeet,这将解决这个问题。字典变量不应该被称为Rates
?这样它才能正确地映射。@Dygestor:是的,绝对正确。显然,今天下午我有点像个木偶:)这个国家不是吗null@Scrobi:是的,但是如果OP需要,他们可以使用字典中的键。将进行编辑以澄清。谢谢@Jon Skeet,我认为,这将解决问题。字典变量不应该被称为Rates
?这样它才能正确地映射。@Dygestor:是的,绝对正确。显然,今天下午我有点像个木偶:)这个国家不是吗null@Scrobi:是的,但是如果OP需要,他们可以使用字典中的键。将编辑以澄清。
// 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();