You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从索引数组动态填充MVVM模型,处理Ryanair API机场数据?

动态填充并处理Ryanair机场API的索引数组数据

嘿,我明白你的问题了——原来的_airports是非索引结构,但现在Ryanair的API返回的是包含机场对象的索引数组,你想不用关心具体索引就能动态填充并提取数据对吧?下面给你两种常见场景的解决方案,适配不同的_airports结构需求:


场景1:保持_airports为可索引的List集合

如果你的需求只是能像_airports[0]那样访问单个机场,同时不需要手动处理API返回的数组索引,直接用JSON反序列化自动转换就行:

首先,确保你有和API返回结构匹配的Airports模型类(根据实际API返回字段调整):

public class Airports
{
    // 用JsonPropertyName映射API返回的字段名,确保匹配
    [JsonPropertyName("code")]
    public string Code { get; set; }
    
    [JsonPropertyName("name")]
    public string Name { get; set; }
    
    [JsonPropertyName("countryCode")]
    public string CountryCode { get; set; }
    
    // 其他API返回的字段...
}

然后修改GetAirports方法,用HttpClient请求并自动反序列化为List:

private readonly HttpClient _httpClient;
private const string _BASEURL = "https://desktopapps.ryanair.com/en-gb/res/stations";
private List<Airports> _airports;

// 推荐通过依赖注入注入HttpClient,避免重复创建
public YourServiceClass(HttpClient httpClient)
{
    _httpClient = httpClient;
}

public async Task<List<Airports>> GetAirports()
{
    if (_airports == null)
    {
        try
        {
            // 发起API请求
            var response = await _httpClient.GetAsync(_BASEURL);
            // 确保请求成功,否则抛出异常
            response.EnsureSuccessStatusCode();
            
            // 自动将API返回的索引数组反序列化为List<Airports>
            _airports = await response.Content.ReadFromJsonAsync<List<Airports>>();
        }
        catch (HttpRequestException ex)
        {
            // 处理请求失败的情况,比如日志记录或自定义异常
            throw new InvalidOperationException("Failed to fetch airport data from API", ex);
        }
        catch (JsonException ex)
        {
            // 处理JSON反序列化失败的情况
            throw new InvalidOperationException("Failed to parse airport data", ex);
        }
    }

    return _airports;
}

为什么这样可行?

  • API返回的JSON数组会被ReadFromJsonAsync<List<Airports>>自动转换成List集合,完全不需要你手动处理数组的索引
  • 之后你可以通过_airports[0]获取第一个机场,或者用LINQ进行更灵活的查询(比如_airports.First(a => a.Code == "DUB")),完全不用关心原始数组的索引名称

场景2:将_airports转换为非索引的键值对字典

如果你需要的是非索引的结构(比如按机场代码快速查找),可以用LINQ动态将数组转换为字典,不需要硬编码任何索引:

修改_airports的类型为Dictionary<string, Airports>,然后调整方法:

private readonly HttpClient _httpClient;
private const string _BASEURL = "https://desktopapps.ryanair.com/en-gb/res/stations";
private Dictionary<string, Airports> _airports;

public YourServiceClass(HttpClient httpClient)
{
    _httpClient = httpClient;
}

public async Task<Dictionary<string, Airports>> GetAirports()
{
    if (_airports == null)
    {
        var response = await _httpClient.GetAsync(_BASEURL);
        response.EnsureSuccessStatusCode();
        
        var airportArray = await response.Content.ReadFromJsonAsync<List<Airports>>();
        
        // 动态将数组转换为字典,用机场代码作为键(可根据需求换成其他唯一属性)
        _airports = airportArray.ToDictionary(a => a.Code, a => a);
    }

    return _airports;
}

优势:

  • 现在_airports是键值对结构,你可以直接通过机场代码获取对象(比如_airports["DUB"]),完全不需要依赖数组索引
  • 转换过程是动态的,只要你的Airports类有对应的属性,就不用关心API返回数组的索引顺序或名称

注意事项

  1. 字段匹配:一定要确保Airports类的属性和API返回的JSON字段匹配,必要时用[JsonPropertyName]特性映射字段名
  2. 异常处理:添加try-catch块处理API请求失败、反序列化失败等异常情况,避免程序崩溃
  3. 重复键处理:如果API返回的数组中有重复的键(比如重复的机场代码),ToDictionary会抛出异常,这时候可以用ToLookup或者手动去重

内容的提问来源于stack exchange,提问作者Wanjia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:49:51