![](/img/trans.png)
[英]How to iterate through a List and convert it to a JSON object using JSON.NET (C# / ASP.NET)
[英]Convert Json into List<T> in C# using Json.NET
我有一个JSON字符串如下
private string jsonCountry = @"{'BD': '880', 'BE': '32', 'BF': '226', 'BG': '359', 'BA': '387', 'BB': '+1-246', 'WF': '681'};
我正在努力实现的目标
class Country
{
public string Countrypfx {get;set;}
public string CountryCode {get;set;}
}
public List<Country> GetData()
{
private string jsonCountry = @"{'BD': '880', 'BE': '32', 'BF': '226', 'BG': '359', 'BA': '387', 'BB': '+1-246', 'WF': '681'};
// Here, I want to return List<Country> object
}
我尝试过的
public Country[] GetCountries()
{
MyCountryData myData = JsonConvert.DeserializeObject<MyCountryData>(jsonCountry);
Country[] countries = myData.data;
return countries;
}
public class Country
{
public string CountryPrefix { get; set; }
public string ContryCode { get; set; }
}
public class MyCountryData
{
public Country[] data { get; set; }
}
有人可以帮我获得所需的输出吗? 谢谢
您的json格式不正确,无法直接将其转换为列表。
首先,您必须将其转换为字典
var dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(jsonCountry);
然后将其转换为所需的列表。
var countries = dict.Select(d => new Country { CountryPrefix = d.Key, CountryCode = d.Value });
这是将json转换为自定义对象列表的方法:
string jsonCountry = @"{'BD': '880', 'BE': '32', 'BF': '226', 'BG': '359', 'BA': '387', 'BB': '+1-246', 'WF': '681'}";
MyCountryData conData = new MyCountryData();
conData.data = JsonConvert.DeserializeObject<Dictionary<string, string>>(jsonCountry)
.Select(x => new Country { CountryPrefix = x.Key, ContryCode = x.Value}).ToArray();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.