使用 Swift JSON 从 TheMovieDB API 获取数据时遇到问题
Trouble getting data from TheMovieDB API with Swift JSON
我是 JSON 的新手,我想开始使用一个简单的应用程序,以便在您输入标题时提供电影概览。我下面的代码 returns 一切都在一个大字符串中。我如何只获得一条信息,例如概览或年份?
在我下面的尝试中,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()
}
首先 JSON 结果永远不会 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")
}
}
强烈建议在 Swift 4.
中使用 Codable
协议和自定义结构
// 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
}
}
我是 JSON 的新手,我想开始使用一个简单的应用程序,以便在您输入标题时提供电影概览。我下面的代码 returns 一切都在一个大字符串中。我如何只获得一条信息,例如概览或年份?
在我下面的尝试中,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()
}
首先 JSON 结果永远不会 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")
}
}
强烈建议在 Swift 4.
中使用Codable
协议和自定义结构
// 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
}
}