【问题标题】:Deserialize Json into list using Json.net C#使用 Json.net C# 将 Json 反序列化为列表
【发布时间】:2016-04-06 07:58:10
【问题描述】:

我有一个 JSON 数据 (http://country.io/names.json),例如:

{"BD": "Bangladesh", "BE": "Belgium", "BF": "Burkina Faso", "BG": "Bulgaria", "BA": "Bosnia and Herzegovina", "BB": "Barbados" }

我想列出类似 CountryCode-CountryName (BD-Bangladesh) 的 json。我如何在 Windows 窗体应用程序上做到这一点。 ?

【问题讨论】:

    标签: c# json list


    【解决方案1】:

    您可以将 JSON 反序列化为 Dictionary 而不是单个对象。这使您可以访问所有代码和名称,如下所示:

    var json = @"{""BD"": ""Bangladesh"", ""BE"": ""Belgium"", ""BF"": ""Burkina Faso"", ""BG"": ""Bulgaria"", ""BA"": ""Bosnia and Herzegovina"", ""BB"": ""Barbados"" }";
    
    var dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
    
    foreach (var item in dict)
    {
        var countryCode = item.Key;
        var countryName = item.Value;
    
        // do whatever you want to do with those two values here
        Console.WriteLine("CountryCode: {0} CountryName: {1}", countryCode, countryName);
    }
    

    在该代码中,它只是将其写入屏幕,但显然,一旦你有了这个循环,你就可以对国家代码和名称做任何你喜欢的事情。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-03
      • 2011-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多