Search code examples
swiftjsondecoder

Swift - Decode specific key using jsonDecoder


I'm not sure how to word my question, but I'm trying to find how to decode not a whole json, but only a specific key without creating multiple models.

JSON example:

{
  "page": 1,
  "results": [
    {
      "poster_path": "/e1mjopzAS2KNsvpbpahQ1a6SkSn.jpg",
      "adult": false,
      "overview": "From DC Comics comes the Suicide Squad, an antihero team of incarcerated supervillains who act as deniable assets for the United States government, undertaking high-risk black ops missions in exchange for commuted prison sentences.",
      "release_date": "2016-08-03",
      "genre_ids": [
        14,
        28,
        80
      ],
      "id": 297761,
      "original_title": "Suicide Squad",
      "original_language": "en",
      "title": "Suicide Squad",
      "backdrop_path": "/ndlQ2Cuc3cjTL7lTynw6I4boP4S.jpg",
      "popularity": 48.261451,
      "vote_count": 1466,
      "video": false,
      "vote_average": 5.91
    },
    ...
  ]
}

I only need to get results. Now I have 2 models:

struct Movies: Codable {
    let results: [MovieResult]?
}

struct MovieResult: Codable {
    let popularity: Double?
    let poster_path: String?
    let backdrop_path: String?
    let title: String?
    let vote_average: Double?
    let overview: String?
    let release_date: String?
}

And getting decoding:

        RESTful.request(path: path, method: "GET", parameters: parameters, headers: nil) { (result) in
            switch result {
            case .failure(let error):
                completion(.failure(.networkingError))
            case .success(let data):
                let jsonDecoder = JSONDecoder()
                do{
                    let popularMovies = try jsonDecoder.decode(Movies.self, from: data)
                    completion(.success(popularMovies))
                } catch (let error) {
                    completion(.failure(.errorDecoding))
                }
            }
        }

Is there a way(using jsonDecoder) to decode it to a single model, since I only need results?


Solution

  • JSON must be decoded always from the root object.

    But there is a very simple solution, declare the Result type

    Result<MovieResult,Error>
    

    and call completion on success

    completion(.success(popularMovies.results))