Swift解析嵌套JSON遇keyNotFound错误:audio_clips字段映射问题
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
CodingKeysenum name: ChangedCodingkeystoCodingKeysin theBodystruct. This tells the decoder to use your custom key mapping instead of the default property name. - Removed redundant
CodingKeysinClips: Since thetitleanddescriptionproperty 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
CodingKeysis spelled with an uppercase 'K'—Swift is case-sensitive here. - Ensure the raw values in your
CodingKeysenum perfectly match the JSON key names (including underscores, casing, and special characters). - Temporarily print the raw JSON structure using
JSONSerializationif you're unsure about key paths or names.
内容的提问来源于stack exchange,提问作者Pulsarman325

