微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Swift-使用jsonDecoder解码特定密钥

如何解决Swift-使用jsonDecoder解码特定密钥

我不确定如何表达我的问题,但是我试图找到如何解码整个json,而不解码整个json,而不创建多个模型。

JSON示例:

{
  "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
    },...
  ]
}

我只需要获得results。 现在我有2个模型:

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

并开始解码:

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

因为我只需要results,有没有一种方法(使用jsonDecoder)将其解码为单个模型?

解决方法

必须始终从根对象解码JSON。

但是有一个非常简单的解决方案,声明Result类型

Result<MovieResult,Error>

并成功致电completion

completion(.success(popularMovies.results))

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。