1

我是使用 JSON 的新手,想开始使用一个简单的应用程序,以便在您输入标题时提供电影概述。我下面的代码在一个大字符串中返回所有内容。我如何只获得一个信息,例如概述或年份?

通过我下面的尝试, print(obj["overview"] as Any)) 打印“nil”并且 print(obj) 看起来像这样:

{
page = 1;
results =     (
            {
        adult = 0;
        "backdrop_path" = "/A0aGxrCGRBuCrDltGYiKGeAUect.jpg";
        "genre_ids" =             (
            53,
            80
        );
        id = 680;
        "original_language" = en;
        "original_title" = "Pulp Fiction";
        overview = "A burger-loving hit man, his philosophical partner, a drug-addled gangster's moll and a washed-up boxer converge in this sprawling, comedic crime caper. Their adventures unfurl in three stories that ingeniously trip back and forth in time.";

当前代码:

    let query = "Pulp+Fiction"
    let urlString = "https://api.themoviedb.org/3/search/movie?api_key={MYAPIKEY}&query=\(query)"

    let url = URL(string: urlString)
    URLSession.shared.dataTask(with:url!) { (data, response, error) in
        if error != nil {
            print(error as Any)
        } else {
            do {
                let parsedData = try JSONSerialization.jsonObject(with: data!) as Any
                if let obj = parsedData as? NSDictionary {

                    print(obj["overview"] as Any)
                    print(obj)

                }
            } catch {
                print("error")
            }            }
        }.resume()
}
4

2 回答 2

2
    // write this extension anywhere in your any swift file
    extension String{
         func toDictionary() -> NSDictionary {
          let blankDict : NSDictionary = [:]
         if let data = self.data(using: .utf8) {
            do {
               return try JSONSerialization.jsonObject(with: data, options: []) as! NSDictionary
                       } catch {
                            print(error.localizedDescription)
                        }
                    }
                    return blankDict
                }
            }
      //now  in your code modify as 
        if  data != nil {
                        let responseString = String(data: data!, encoding: .utf8)!
                        if(responseString != "")
                        {
                         //convert response string into dictionary using extended method
                         let responseValues = responseString.toDictionary()
                         //access value using keyPath using
                         let value = responseValues.value(forKeyPath: "key.key2")
//where key2 is the target key which is inside the value of key 
                     }
        }
于 2018-05-11T19:19:54.007 回答
0

首先 JSON 结果是 never Any。正如评论中已经提到的,根对象是一个字典

if let parsedData = try JSONSerialization.jsonObject(with: data!) as? [String:Any],

overview在键的数组中results

   let results = parsedData["results"] as? [[String:Any]] {

您必须遍历数组以获取键的值overview

      for result in results {
          print(result["overview"] as? String ?? "no value for key overview") 
      }
}

强烈建议Codable在 Swift 4 中使用协议和自定义结构。

于 2018-05-11T18:55:24.100 回答