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

Swift解析嵌套JSON遇keyNotFound错误:audio_clips字段映射问题

Fixing the keyNotFound Error When Parsing Nested JSON in Swift

Hey there! I see exactly what's causing that frustrating keyNotFound error for the "audioclips" key—let's break it down and fix it.

The Root Cause

Your Body struct uses an enum named Codingkeys (with a lowercase 'k'), but Swift's Decodable protocol requires the enum to be named CodingKeys (uppercase 'K') for the JSON key mapping to work. Since the enum name is incorrect, the JSON decoder ignores your custom mapping (audioclips = "audio_clips") and tries to look for a key named "audioclips" directly in the JSON (which doesn't exist—your JSON has "audio_clips" instead). That's why you're getting the keyNotFound error.

Fixed Swift Code

Here's the corrected version of your code, with the critical fix and a minor cleanup:

import UIKit

class PodcastViewController: UIViewController {
    struct Root : Decodable {
        var body : Body
    }
    
    struct Body : Decodable {
        // Fixed: Renamed to CodingKeys (uppercase K)
        enum CodingKeys : String, CodingKey {
            case audioclips = "audio_clips"
        }
        var audioclips : [Clips]
    }
    
    struct Clips : Decodable{
        // You can remove this enum entirely since property names match JSON keys
        // enum CodingKeys : String, CodingKey {
        //     case title = "title"
        //     case description = "description"
        // }
        var title : String
        var description : String
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        let url = URL(string: "https://api.audioboom.com/channels/5019730/audio_clips?api_version=1")!
        URLSession.shared.dataTask(with: url) {data, response, error in
            if let data = data {
                print("DATA EXISTS")
                do {
                    let result = try JSONDecoder().decode(Root.self, from: data)
                    // Access the title and description once parsed successfully
                    if let firstClip = result.body.audioclips.first {
                        print("Title: \(firstClip.title)")
                        print("Description: \(firstClip.description)")
                    }
                } catch {
                    print(error)
                }
            }
        }.resume()
    }
}

Key Changes Explained

  • Fixed CodingKeys enum name: Changed Codingkeys to CodingKeys in the Body struct. This tells the decoder to use your custom key mapping instead of the default property name.
  • Removed redundant CodingKeys in Clips: Since the title and description property names exactly match the JSON keys, this enum is unnecessary and can be safely removed to clean up your code.

Quick Tips for Future Decoding Issues

If you run into similar problems again, keep these checks in mind:

  • Always verify CodingKeys is spelled with an uppercase 'K'—Swift is case-sensitive here.
  • Ensure the raw values in your CodingKeys enum perfectly match the JSON key names (including underscores, casing, and special characters).
  • Temporarily print the raw JSON structure using JSONSerialization if you're unsure about key paths or names.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 18:58:12