【发布时间】:2018-10-23 21:37:13
【问题描述】:
我在访问存储在 JSON API 内的信息时遇到问题,只要它位于 [] 括号内而不是 {} 括号内。我正在尝试搜索数组并找到与"job": "director" 匹配的{} 集。问题是,如果我不使用诸如 CollectionView 之类的 IndexPath 视图,我将无法访问位于 [] 括号内的信息。
JSON:
"crew": [
{
"credit_id": "57ea3a02c3a3687edc00080a",
"department": "Directing",
"gender": 2,
"id": 51329,
"job": "Director",
"name": "Bradley Cooper",
"profile_path": "/z5LUl9bljJnah3S5rtN7rScrmI8.jpg"
},
{
"credit_id": "57ea3a14c3a3687ff9007bd7",
"department": "Writing",
"gender": 2,
"id": 51329,
"job": "Screenplay",
"name": "Bradley Cooper",
"profile_path": "/z5LUl9bljJnah3S5rtN7rScrmI8.jpg"
},
{
"credit_id": "57ea3a27925141108f008807",
"department": "Writing",
"gender": 2,
"id": 224385,
"job": "Screenplay",
"name": "Will Fetters",
"profile_path": null
}
],
这是我的部分代码:
struct Cast: Codable {
let character: String
let name: String
let profile_path: String?
}
struct Crew: Codable {
let name: String
let profile_path: String?
let job: String
}
func loadCredits() {
let id = filmId
let apiKey = ""
let url = URL(string: "https://api.themoviedb.org/3/movie/\(id)/credits?api_key=\(apiKey)")
let request = URLRequest(
url: url! as URL,
cachePolicy: URLRequest.CachePolicy.reloadIgnoringLocalCacheData,
timeoutInterval: 10 )
let session = URLSession (
configuration: URLSessionConfiguration.default,
delegate: nil,
delegateQueue: OperationQueue.main
)
let task = session.dataTask(with: request, completionHandler: { (dataOrNil, response, error) in
if let data = dataOrNil {
do { let credit = try! JSONDecoder().decode(Credits.self, from: data)
self.filmCast = credit.cast
self.filmCrew = credit.crew
self.castCollection.reloadData()
}
}
self.castCollection.reloadData()
})
task.resume()
}
我可以使用它来通过索引路径访问信息:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = castCollection.dequeueReusableCell(withReuseIdentifier: "castCell", for: indexPath) as! CastCell
let credit = filmCast[indexPath.row]
let name = credit.name
cell.castName.text = name
return cell
}
但如果数据没有位于诸如 UICollectionView 之类的 IndexPath 视图中,我在搜索数据时遇到了麻烦。
因此,如果我想在我正在尝试的集合视图之外搜索 job 即 Director:
if filmCrew.job == "Director" {
perform action here
}
我收到错误消息:
“[DetailsView.Crew]”类型的值没有成员“job”
所以我的问题是如何正确搜索 JSON 数组以根据匹配值找到匹配的数据 {}。抱歉,如果这个问题听起来很愚蠢或令人困惑,自从使用字典和数组以来,我就遇到了这个问题。当我在表和集合视图中对其进行索引时,它总是可以正常工作,但我似乎无法弄清楚如何筛选数组。
【问题讨论】: