在Swift中获取特定的json数据

时间:2017-06-11 10:49:33

标签: 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转到回复>例子

1 个答案:

答案 0 :(得分:0)

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

获得所有学分的列表后,只需查找具有生产者

作业的学分
MovieMDB.credits(apiKey, movieID: movieID){
    apiReturn, credits in


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

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

decoder_outputs