Home>

Currently, a Model for receiving the response from JSON1 below is automatically created from the site,
I left only the data I wanted to get.
In JSON2, I received the response as shown below, but in JSON1, Cast and Crew are in the array of Credits, so I was wondering how to receive the response in ViewController, so please teach me.


JSON1
{
  "id": 597,
  "credits": {
    "cast": [
      {
        "id": 6193,
        "name": "Leonardo DiCaprio"
      }
    ],,


    "crew": [
      {
        "department": "Directing",
        "id": 2710,
        "job": "Director",
        "name": "James Cameron"
      }
    ]
  }
}
Model1
import Foundation
// MARK: --Welcome
struct CastModel: Codable {
    let id: Int
    let credits: Credits
}
// MARK: --Credits
struct Credits: Codable {
    let cast: [Cast]
    let crew: [Crew]
}
// MARK: --Cast
struct Cast: Codable {
    let id: Int
    let name: String
}
// MARK: --Crew
struct Crew: Codable {
    let department: String
    let id: Int
    let job, name: String}
JSON2&Model2
// JSON
{
  "results": [
    {
      "id": 597,
      "title": "Titanic",
      "release_date": "1997-11-18",
      "original_language": "en",
      "original_title": "Titanic",
      "overview":
      "poster_path": "/9THZ0bjPRc4qP229dmItJcQTQKU.jpg"
    },


  ]
}
-------------------------------------------------- ------
// Model
import Foundation
struct MovieItem: Codable {
    let id: Int
    let title: String
    let release_date: String?
    let poster_path: String?
    let overview: String?
    let original_language: String?
}
struct MovieStruct: Codable {
    let results: [MovieItem]
}
class FirstViewController: UIViewController {
    @IBOutlet weak var table: UITableView!
    private var items: [MovieItem] = [MovieItem] ()
    override func viewDidLoad () {
        super.viewDidLoad ()
        fechData ()
    }
    func fechData () {
        items.removeAll ()
        URLSession.shared.dataTask (with: URL (string: "https://api.themoviedb.org/3/movie/popular?api_key=########&language=ja&page=1") !,
                                   completionHandler: {data, response, error in
                                    guard let data = data else {
                                        print (error? .localizedDescription ?? "Unknown error")
                                        return
                                    }
                                     var result: MovieStruct?do {
                                        result = try JSONDecoder (). Decode (MovieStruct.self, from: data)
                                    }
                                    catch {
                                        print ("JSON perse error")
                                    }
                                    guard let finalResult = result else {
                                        return
                                    }
                                    let newMovies = finalResult.results
                                    self.items.append (contentsOf: newMovies)
                                    DispatchQueue.main.async {
                                        self.table.reloadData ()
                                    }
        }) .resume ()
    }
}
Draft code
private var items: [CastModel] = [CastModel] ()
func fechData () {
        items.removeAll ()
// The movieID will be the one obtained from another VIewController.
        URLSession.shared.dataTask (with: URL (string: "https://api.themoviedb.org/3/movie/\(movieID)?api_key=#########&language=ja&append_to_response=credits") !,
                                   completionHandler: {data, response, error in
                                    guard let data = data else {
                                        print (error? .localizedDescription ?? "Unknown error")
                                        return
                                    }
                                     var result: Credits?
                                    do {
                                        result = try JSONDecoder (). decode (Credits.self, from: data)
                                    }
                                    catch {
                                        print ("JSON perse error")
                                    }
                                    guard let finalResult = result else {
                                        return
                                    }
                                    let newMovies = finalResult.cast
                                    self.items.append (contentsOf: newMovies)
                                    print (newMovies)
                                    DispatchQueue.main.async {
                                        self.table.reloadData ()
                                    }
        }) .resume ()
    }
  • Answer # 1

    I finally got it here with reference to what Tsukuba Depot taught me.
    I will put together the completed form for other people.

    import Foundation
    struct CastModel: Codable {
        let id: Int
        let credits: Credits
    }
    struct Credits: Codable {
        let cast: [Cast]
        let crew: [Crew]
    }
    struct Cast: Codable {
        let id: Int
        let name: String
    }
    struct Crew: Codable {
        let department: String
        let id: Int
        let job, name: String
    }
    private var castItems: [Credits] = [Credits] ()
    func fechData () {
            castItems.removeAll ()
            URLSession.shared.dataTask (with: URL (string: "https://api.themoviedb.org/3/movie/635302?api_key=########&language=ja&append_to_response=credits") !,
                                       completionHandler: {data, response, error in
                                        guard let data = data else {
                                            print (error? .localizedDescription ?? "Unknown error")
                                            return
                                        }
                                        var creditsResult: CastModel?
                                        do {
                                            creditsResult = try JSONDecoder (). decode (CastModel.self, from: data)
                                        }
                                        catch {
                                            print ("JSON perse error")
                                        }
                                        guard let finalResult = creditsResult else {
                                            return
                                        }
                                        let newMovies = finalResult.credits
                                        self.castItems.append (newMovies)
                                        print (newMovies)
                                        DispatchQueue.main.async {
                                        }
            }) .resume ()
        }
    }