【问题标题】:How to fix no value associated with key CodingKeys error when parsing JSON in swift如何在快速解析 JSON 时修复与键 CodingKeys 错误关联的无值
【发布时间】:2021-10-21 21:21:03
【问题描述】:

我正在尝试使用 swift 解析来自 API 的数据。

JSON

{
    "page": 1,
    "results": [{
        "id": 597,
        "overview": "101-year-old...",
        "title": "Titanic"
    }, {
        "id": 598,
        "overview": "Another one...",
        "title": "Titanic II"
    }, {
        "id": 599,
        "overview": "Another one...",
        "title": "Titanic III"
    }]
}

型号


import SwiftUI

struct APIResult: Codable {
    var data: APIMovieData
}

struct APIMovieData: Codable {
    var count: Int
    var results: [Movie]
}

struct Movie: Identifiable, Codable {
    var id: Int
    var title: String
    var overview: String
}

查看模型

func searchMovies(){
  
        let originalQuery = searchQuery.replacingOccurrences(of: " ", with: "%20")
        let url = "https://api.themoviedb.org/3/search/movie?api_key=XXXXc&query=\(originalQuery)"
        let session = URLSession(configuration: .default)
        session.dataTask(with: URL(string: url)!) { (data, _, err) in

            if let error = err{
                print(error.localizedDescription)
                return
            }
            
            guard let APIData = data else{
                print("no data found")
                return
            }
            
            do{
                
                // decoding API Data....
                
                let movies = try JSONDecoder().decode(APIResult.self, from: APIData)
                
                DispatchQueue.main.async {
                    
                    if self.fetchedMovies == nil{
                        self.fetchedMovies = movies.data.results
                    }
                }
            }
            catch{
                print(error)
            }
        }
        .resume()
    }

但是当我运行我的应用程序时,搜索失败:

debugDescription: "No value associated with key CodingKeys(stringValue: "data", intValue: nil) ("data").", underlyingError: nil))

看看这个question,问题似乎是我的模型与 JSON 结构不匹配。但是,为 JSON 构建模型的正确方法是什么?

【问题讨论】:

  • But what would be the right way to structure my Model for the JSON?:您可以使用app.quicktype.io 或使用自定义init(from:) 将您的JSON 解析为您的目标结构。否则,你也可以做相反的事情。创建一个具有“足够”值的APIResult,然后调用JSONEncoder(),看看生成的JSON 是什么样的,以及它与你得到的JSON 有何不同。它可能会帮助您了解整个结构以及“匹配”的工作原理(毕竟,没有魔法,它是逻辑)。

标签: json swift


【解决方案1】:

正如您所指出的,您的 JSON 结构需要映射您的 Codable 元素。例如,您的 Codable 以 data 开头,它根本没有在 JSON 结构中表示。您的 JSON 中也没有任何 count


let jsonData = """
{
    "page": 1,
    "results": [{
        "id": 597,
        "overview": "101-year-old...",
        "title": "Titanic"
    }, {
        "id": 598,
        "overview": "Another one...",
        "title": "Titanic II"
    }, {
        "id": 599,
        "overview": "Another one...",
        "title": "Titanic III"
    }]
}
""".data(using: .utf8)!

struct APIResult: Codable {
    var page: Int
    var results: [Movie]
}

struct Movie: Codable {
    var id: Int
    var overview: String
    var title: String
}

do {
    let apiResult = try JSONDecoder().decode(APIResult.self, from: jsonData)
    let movies = apiResult.results
    print(movies)
} catch {
    print(error)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-28
    • 1970-01-01
    • 2021-10-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多