将Json对象反序列化为.NET对象

时间:2016-05-27 13:43:00

标签: 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 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中的关键。如何将此对象反序列化为ListArrayCountry个对象。我愿意使用任何JSON转换器

1 个答案:

答案 0 :(得分:4)

只需对响应进行建模:

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();