我有一个如下的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; }
}
有人可以帮助我获得所需的输出吗?谢谢
答案 0 :(得分:4)
您的json格式不正确,无法直接将其转换为列表。
首先,您必须将其转换为字典
var dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(jsonCountry);
然后将其转换为所需的列表。
var countries = dict.Select(d => new Country { CountryPrefix = d.Key, CountryCode = d.Value });
答案 1 :(得分:0)
以下是将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();