【问题标题】:Using JSON Arrays in swift快速使用 JSON 数组
【发布时间】: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 视图中,我在搜索数据时遇到了麻烦。

因此,如果我想在我正在尝试的集合视图之外搜索 jobDirector

if filmCrew.job == "Director" {
 perform action here
  }

我收到错误消息:

“[DetailsView.Crew]”类型的值没有成员“job”

所以我的问题是如何正确搜索 JSON 数组以根据匹配值找到匹配的数据 {}。抱歉,如果这个问题听起来很愚蠢或令人困惑,自从使用字典和数组以来,我就遇到了这个问题。当我在表和集合视图中对其进行索引时,它总是可以正常工作,但我似乎无法弄清楚如何筛选数组。

【问题讨论】:

    标签: ios json swift


    【解决方案1】:

    您的条件需要遍历整个filmCrew 数组并找到第一个拥有"Director" 工作的用户,幸运的是有一种方法可以做到这一点。

    if let director = filmCrew.first(where: { $0.job == "Director" }) {
        //perform action here
    }
    

    【讨论】:

    • 这行得通,谢谢!现在,如果我试图访问jobscreenplay 的每个实例,我会使用contains 而不是first
    • contains 只会告诉您是否至少有一个实例具有jobscreenplay。您可能需要filter,它将过滤数组并返回一个新数组,其中包含jobscreenplay 的所有用户。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-31
    • 1970-01-01
    • 2018-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多