Home > Software design >  Error when decoding a JSON file from the youtube API
Error when decoding a JSON file from the youtube API

Time:10-19

I'm new to swift programming and I'm following a tutorial to practice it. In the tutorial there is a part were I'm required to use the youtube API in order to display videos related to a query I'm sending ("Harry Potter" for instance). This is the code for that:

func getMovie(with query: String, completion: @escaping (VideoElement) -> Void) {
    guard let query = query.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) else { return }
    guard let url = URL(string: "\(Constants.Youtube_Base_URL)q=\(query)&key=\(Constants.Youtube_API_KEY)") else { return }
    
    let task = URLSession.shared.dataTask(with: URLRequest(url: url)) { data, _, error in
        guard let data = data, error == nil else { return }
        
        do {
            let results = try JSONDecoder().decode(YoutubeSearchResponse.self, from: data)
            print(results)
        }
        catch {
            print(error)
        }
    }
    task.resume()
}

And here is the ViewModel I'm using to store all the data

import Foundation

struct YoutubeSearchResponse: Codable {
    let items: [VideoElement]
}

struct VideoElement: Codable {
    let kind: String
    let etag: String
    let id: IdVideoElement
}

struct IdVideoElement: Codable {
    let kind: String
    let videoId: String
}

And the JSON object I'm trying to decode looks something like this

{
"kind": "youtube#searchListResponse",
"etag": "wFHpGVWdte2UR9vabzgTBGRw5-c",
"nextPageToken": "CAUQAA",
"regionCode": "CO",
"pageInfo": {
  "totalResults": 1000000,
  "resultsPerPage": 5
},
"items": [
  {
    "kind": "youtube#searchResult",
    "etag": "nn_Ih6r95JKAesBbHpycaDYycYQ",
    "id": {
      "kind": "youtube#video",
      "videoId": "H5v3kku4y6Q"
    }
  },
  {
    "kind": "youtube#searchResult",
    "etag": "g7MBprSF3MjksecVRh0Up_Dcxcg",
    "id": {
      "kind": "youtube#video",
      "videoId": "bt_pJG3YZpc"
    }
   }
  ] 
 }

The main problem is, that I'm getting this error:

keyNotFound(CodingKeys(stringValue: "videoId", intValue: nil), Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "items", intValue: nil), _JSONKey(stringValue: "Index 1", intValue: 1), CodingKeys(stringValue: "id", intValue: nil)], debugDescription: "No value associated with key CodingKeys(stringValue: "videoId", intValue: nil) ("videoId").", underlyingError: nil))

And I have no idea why. I'm wondering what is causing this error and hoy may I fix it

CodePudding user response:

Just make your videoID to optional and the problem will gone

struct IdVideoElement: Codable {
let kind: String
let videoId: String?

}

  • Related