简体   繁体   English

使用Json.net C#将Json反序列化为列表

[英]Deserialize Json into list using Json.net C#

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

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

I want to list that json like CountryCode-CountryName (BD-Bangladesh) . 我想列出该json,例如CountryCode-CountryName(BD-Bangladesh)。 How do I do that on windows form app. 我该如何在Windows窗体应用程序上做到这一点。 ?

You could deserialise the JSON into a Dictionary instead of a single object. 您可以将JSON反序列化为Dictionary而不是单个对象。 This gives you access to all the codes and names, like so: 这使您可以访问所有代码和名称,如下所示:

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

In that code it simply writes it to the screen, but obviously once you have that loop in place you can do whatever you like with the country code and name. 在该代码中,它只是将其写入屏幕,但是很显然,一旦有了该循环,就可以使用国家/地区代码和名称进行任何操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM