简体   繁体   English

快速解析 JSON 时如何修复与键 CodingKeys 错误相关的没有值

[英]How to fix no value associated with key CodingKeys error when parsing JSON in swift

I'm trying to parse data from an API using swift.我正在尝试使用 swift 解析来自 API 的数据。

JSON 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"
    }]
}

Model模型


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
}

View Model查看模型

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()
    }

But when I run my app the search fails with:但是当我运行我的应用程序时,搜索失败:

debugDescription: "No value associated with key CodingKeys(stringValue: "data", intValue: nil) ("data").", underlyingError: nil)) debugDescription:“没有与键 CodingKeys 关联的值(stringValue:“data”,intValue:nil)(“data”)。”,underlyingError:nil))

Looking at this question it seems like the problem is my model doesn't match the JSON structure.看着这个问题,问题似乎是我的模型与 JSON 结构不匹配。 But what would be the right way to structure my Model for the JSON?但是,为 JSON 构建我的模型的正确方法是什么?

As you pointed out, your JSON structure needs to map your Codable elements.正如您所指出的,您的 JSON 结构需要映射您的 Codable 元素。 For example, your Codable starts with data , which isn't represented in the JSON structure at all.例如,您的 Codable 以data开头,它根本没有在 JSON 结构中表示。 There also isn't any count in your 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)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM