【问题标题】:Deserializing the Json object to .NET object将 Json 对象反序列化为 .NET 对象
【发布时间】:2016-05-27 13:43:00
【问题描述】:

我有以下由 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 转换器

【问题讨论】:

  • 将其反序列化为Dictionary<string,Country>,然后该字典的Values 将为您提供您的收藏。

标签: c# .net json deserialization


【解决方案1】:

只需像这样模拟响应:

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

【讨论】:

  • 谢谢@Jon Skeet,我想,这会解决问题
  • Dictionary 变量不应该被称为Rates 吗?以便正确映射。
  • @Dygestor:是的,绝对的。显然我今天下午有点像个布偶:)
  • Country.ShortCode 不会为空
  • @Scrobi:是的,但是如果 OP 需要,他们可以使用字典中的键。将编辑澄清。
猜你喜欢
  • 2017-01-28
  • 1970-01-01
  • 2012-03-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-25
  • 1970-01-01
相关资源
最近更新 更多