简体   繁体   中英

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.

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

Looking at this question it seems like the problem is my model doesn't match the JSON structure. But what would be the right way to structure my Model for the JSON?

As you pointed out, your JSON structure needs to map your Codable elements. For example, your Codable starts with data , which isn't represented in the JSON structure at all. There also isn't any count in your JSON.


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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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