GetAirports
让我填写_airports
如果要取消索引,这意味着如果我使用_airport[0]
但是,使用此公共API链接https://desktopapps.ryanair.com/en-gb/res/stations获取机场会使用分配了对象的索引数组。如何在不知道实际索引名称的情况下动态填充 _airports
和解压缩?
public async Task<List<Airports>> GetAirports()
{
string url = _BASEURL;
if( _airports == null)
_airports = await GetAsync<List<Airports>>(url);
return _airports;
}
GetAsync功能:
protected async Task<T> GetAsync<T>(string url)
{
using (HttpClient client = CreateHttpClient())
{
try
{
var json = await client.GetStringAsync(url);
return await Task.Run(() => JsonConvert.DeserializeObject<T>(json));
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
return default(T);
}
}
}
机场型号:
public class Airports
{
public string Name { get; set; }
public string Country { get; set; }
public string TimeZone { get; set; }
public string Latitude { get; set; }
public string Longitude { get; set; }
}
来自API
"AAL":{
"name":"Aalborg Airport",
"country":"DK",
"timeZone":"DK",
"latitude":"570535N",
"longitude":"0095100E"
},
"AAR":{...}
答案 0 :(得分:2)
以下是基于API返回的数据格式的解决方法。
向模型添加其他属性以保存密钥/代码,例如AAL
public class Airport { //<-- note the name change of the model
public string Code { get; set; }
public string Name { get; set; }
public string Country { get; set; }
public string TimeZone { get; set; }
public string Latitude { get; set; }
public string Longitude { get; set; }
}
接下来重构解析以使用Dictionary<string, Airport>
,然后提取KeyValuePair
以返回所需的类型
public async Task<List<Airport>> GetAirportsAsync() { //<-- note the name change
string url = _BASEURL;
if( _airports == null) {
var data = await GetAsync<Dictionary<string, Airport>>(url);
_airports = data.Select(_ => {
var code = _.Key;
var airport = _.Value;
airport.Code = code;
return airport;
}).ToList();
}
return _airports;
}