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

Swift中遍历航班JSON响应对象的技术疑问

解决航班JSON遍历与TableView填充问题

1. 修正JSON解析逻辑

当前解析代码使用try?会隐藏错误,且未正确处理航班数组。调整后代码可正确提取所有航班数据:

func parseJSON(_ flightDataPassedIn: Data) -> [Scheduled_Arrivals]? {
    let decoder = JSONDecoder()
    do {
        // 若JSON外层是字典结构,按此解析;若直接是FlightData对象,改为decode(FlightData.self, from: ...)
        let decodedDict = try decoder.decode([String:FlightData].self, from: flightDataPassedIn)
        
        // 合并所有FlightData实例中的scheduled_arrivals数组
        var allFlights = [Scheduled_Arrivals]()
        for (_, flightData) in decodedDict {
            if let arrivals = flightData.scheduled_arrivals {
                allFlights.append(contentsOf: arrivals)
            }
        }
        return allFlights
    } catch {
        print("解析错误:\(error)")
        return nil
    }
}

2. 遍历打印航班数据(调试用)

拿到合并后的航班数组后,循环打印字段用于调试:

// 传入你的航班Data数据调用解析方法
if let flights = parseJSON(yourFlightData) {
    for flight in flights {
        print("航班标识:\(flight.ident ?? "无")")
        print("航空公司:\(flight.`operator` ?? "无")")
        print("出发机场:\(flight.origin?.code_iata ?? "无")")
        print("到达机场:\(flight.destination?.code_iata ?? "无")")
        print("航班状态:\(flight.status ?? "未知")")
        print("------------------------")
        // 按需添加更多字段打印
    }
}

3. 填充TableView Cell

步骤1:定义数据源数组

在ViewController中声明全局数组存储航班数据:

var flightsArray: [Scheduled_Arrivals] = []

步骤2:更新数据并刷新TableView

获取到解析后的数据后,更新数组并回到主线程刷新UI:

if let flights = parseJSON(yourFlightData) {
    self.flightsArray = flights
    DispatchQueue.main.async {
        self.tableView.reloadData()
    }
}

步骤3:实现TableView数据源方法

extension YourViewController: UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return flightsArray.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        // 假设已自定义FlightCell并设置复用标识
        let cell = tableView.dequeueReusableCell(withIdentifier: "FlightCell", for: indexPath) as! FlightCell
        let flight = flightsArray[indexPath.row]
        
        // 填充Cell的UI元素
        cell.flightNumberLabel.text = flight.flight_number ?? "无"
        cell.airlineLabel.text = flight.`operator` ?? "无"
        cell.originLabel.text = flight.origin?.code_iata ?? "无"
        cell.destinationLabel.text = flight.destination?.code_iata ?? "无"
        cell.statusLabel.text = flight.status ?? "未知"
        
        return cell
    }
}

注意事项

  • 若JSON外层不是字典,而是直接FlightData对象,解析时需改为let decodedData = try decoder.decode(FlightData.self, from: flightDataPassedIn),直接取decodedData.scheduled_arrivals即可。
  • 所有可选字段使用时需做空值处理,避免崩溃。
  • 网络请求需在后台线程执行,UI刷新必须回到主线程。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 15:18:14