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

Swift使用Struct解码JSON返回nil,调用News API获取数据异常求助

问题排查与修复方案

核心问题分析

你的代码解码失败主要有三个原因:

  • 缺少必填字段映射:News API的top-headlines接口返回的JSON顶级字段包含status、totalResults、articles,但你的ArticleList结构体只定义了其中两个,缺少totalResults,导致JSONDecoder无法完成解码。
  • 字段可选性不匹配:API返回的部分文章中description字段可能为null,但你将其定义为非可选的String,解码时遇到null就会失败。
  • 错误处理缺失:使用try?会直接吞掉解码错误,无法得知具体失败原因。

修改后的代码

1. 修正Decodable结构体

import Foundation

struct ArticleList: Decodable {
    let status: String
    let totalResults: Int // 新增API返回的必填字段
    let articles: [Article]
}

struct Article: Decodable {
    let title: String
    let description: String? // 改为可选类型,兼容null值
}

2. 完善WebService的错误处理

import Foundation

class Webservice {
    
    func getArticles(url: URL, completion: @escaping ([Article]?) -> ()) {
        
        print("URL: \(url)")
        
        URLSession.shared.dataTask(with: url) { data, response, error in
            if let error = error {
                print(error.localizedDescription)
                completion(nil)
                return
            }
            
            guard let data = data else {
                print("未获取到有效数据")
                completion(nil)
                return
            }
            
            do {
                let articleList = try JSONDecoder().decode(ArticleList.self, from: data)
                completion(articleList.articles)
                print(articleList.articles)
            } catch {
                // 打印具体解码错误,快速定位问题
                print("解码失败详情:\(error)")
                completion(nil)
            }
        }.resume()
        
    }
    
}

修复说明

  1. 新增totalResults字段:完全匹配API返回的JSON结构,确保解码能正常完成。
  2. 将description改为可选类型:处理API中部分文章无描述的情况,避免因字段为null导致解码失败。
  3. 替换try?为do-catch:捕获并打印具体的解码错误,后续遇到类似问题可以直接通过错误信息定位问题点。

内容的提问来源于stack exchange,提问作者M. Holm

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 00:15:34