GetAirports
让我填写 _airports
如果要取消索引,这意味着如果我使用 _airport[0]
也可以获得机场。
但是通过这个公共(public) 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":{...}
最佳答案
这是一个基于从 API 返回的数据格式的解决方法。
向模型添加一个额外的属性来保存 key /代码,如 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
s 返回想要的类型
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;
}
关于c# - 从索引数组动态填充 mvvm 模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50045465/