json - 在 Swift 中获取特定的 json 数据

标签 json swift

我正在使用一个 API 来获取电影中的工作人员列表。为了得到我正在使用这个功能:

MovieMDB.credits(apiKey, movieID: movieID){
            apiReturn, credits in
            if let credits = credits{
                for crew in credits.crew{
                    print(crew.job)
                    print(crew.name)

                }

            }
        }

这会打印作业和工作人员的列表。但我只想要这部电影的制片人。

调用的函数:

  ///Get the cast and crew information for a specific movie id.
  public  class func credits(_ api_key: String!, movieID: Int!, completion: @escaping (_ clientReturn: ClientReturn, _ credits: MovieCreditsMDB?) -> ()) -> (){
    Client.Movies(String(movieID) + "/credits", api_key: api_key, page: nil, language: nil){
      apiReturn in
      var credits: MovieCreditsMDB?
      if(apiReturn.error == nil){
        credits = MovieCreditsMDB.init(results: apiReturn.json!)
      }
      completion(apiReturn, credits)
    }
  }

这是 json 文件的开头:

{
  "id": 550,
  "cast": [
    {
      "cast_id": 4,
      "character": "The Narrator",
      "credit_id": "52fe4250c3a36847f80149f3",
      "gender": 2,
      "id": 819,
      "name": "Edward Norton",
      "order": 0,
      "profile_path": "/eIkFHNlfretLS1spAcIoihKUS62.jpg"
    },

这是我想要的数据:

"crew": [
    {
      "credit_id": "56380f0cc3a3681b5c0200be",
      "department": "Writing",
      "gender": 0,
      "id": 7469,
      "job": "Screenplay",
      "name": "Jim Uhls",
      "profile_path": null
    },
    {
      "credit_id": "52fe4250c3a36847f8014a05",
      "department": "Production",
      "gender": 0,
      "id": 7474,
      "job": "Producer",
      "name": "Ross Grayson Bell",
      "profile_path": null

我需要制作人的名字。有人知道如何获取该特定数据吗? Link to json转到响应>示例

最佳答案

您只需过滤结果并仅使用/返回您想要的结果。

一旦你有了所有制作人员的列表,只需寻找担任制片人的人即可

 MovieMDB.credits(apiKey, movieID: movieID){
        apiReturn, credits in

        var producer: [String:AnyObject]?
        if let credits = credits {
            for crew in credits.crew {
                if crew.job == "Producer" {
                     producer = crew
                     break
                }
            }
        }
        // here check producer is not nil to ensure it was found
    }

您还可以使用过滤器缩短此代码:

MovieMDB.credits(apiKey, movieID: movieID){
    apiReturn, credits in


    if let credits = credits {
        let producer = credits.filter({ $0.job == "Producer" })
    }
}

关于json - 在 Swift 中获取特定的 json 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44482965/

相关文章:

swift - Firestore 批处理设置仅插入最后一项

javascript - JSON解析: Uncaught SyntaxError: Unexpected token e

ios - @IBInspectable NSLayoutConstraint 不工作 Xcode 8.2.1 (8C1002)

swift - 更改背景颜色但保持 UISwitch "On"状态的色调

javascript - 更改数组的键名中的对象

ios - Swift - 无法将类型 'UINavigationController' 的值转换为 'MapViewController'

ios - UICollectionView — 缩放单元格以适合屏幕

javascript - 如何包含来自另一个 php 文件的 php 验证函数

json - Golang json解析

javascript - Angular Js ng-repeat无法使用ajax从json数组获取输出