我有一个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();