此代码从数据库中读取ID和电影类型。我需要遍历这些信息并计算id / genres信息。我现在硬编码了:
let url = URL(string: "https://api.themoviedb.org/3/genre/movie/list?api_key=818396bc0172f0f1d446cb4ffc92b7d8&language=en-US")
do {
let allData = try Data(contentsOf: url!)
let info = try JSONSerialization.jsonObject(with: allData, options: JSONSerialization.ReadingOptions.allowFragments) as! [String : AnyObject]
if let results = info["genres"] {
print(results)
for x in 0...18 { // here
let id = results[x] as! [String : AnyObject]
print(id)
}
}
} catch {
}
答案 0 :(得分:1)
我看到genres
是一个JSONArray,因此您应该将其转换为字典数组并使用for - in
来访问该数组中的每个项目:
let url = URL(string: "https://api.themoviedb.org/3/genre/movie/list?api_key=818396bc0172f0f1d446cb4ffc92b7d8&language=en-US")
do {
let allData = try Data(contentsOf: url!)
let info = try JSONSerialization.jsonObject(with: allData, options: JSONSerialization.ReadingOptions.allowFragments) as! [String: Any]
if let results = info["genres"] as? [[String: Any]] {
print(results)
for id in results {
print(id)
}
}
} catch {
}