【问题标题】:filtering JSON data in swift快速过滤 JSON 数据
【发布时间】:2017-11-25 17:43:11
【问题描述】:

我正在尝试解析我的 JSON 数据并仅将那些对象附加到满足指定条件的数组中。目前我已经注释掉了从 API 中获取所有对象并将它们添加到数组中的代码。但是,我想限制它,以便它只为“license_author”键附加具有“wger.de”值的对象。

但是我在网上遇到错误:

if eachExercise["license_author"] == "wger.de"

二元运算符“==”不能应用于“任何?”类型的操作数和“字符串”。 但是我仍然想将它保留为 Any 对象,因为我想从我的 API 中获取字符串和整数数据。

这是我的 parseData() 函数的代码:

func parseData() {

    fetchedExercise = []

    let urlPath = "https://wger.de/api/v2/exercise/?format=json&language=2&status=2"
    let url = URL(string: urlPath)!

    let task = URLSession.shared.dataTask(with: url) { (data, response, error) in

        if error != nil {
            print("Error while parsing JSON")
        }
        else {

            do {
                if let data = data,
                    let fetchedData = try JSONSerialization.jsonObject(with: data, options: .mutableLeaves) as? [String:Any],
                    let exercises = fetchedData["results"] as? [[String: Any]] {

                    // WORKING CODE
                    /*
                    for eachExercise in exercises
                    {

                        let name = eachExercise["name"] as! String
                        let description = eachExercise["description"] as! String

                        self.fetchedExercise.append(Exercise(name: name, description: description))

                    }
                    */

                    // TESTING
                    for eachExercise in exercises {
                        if eachExercise["license_author"] == "wger.de" {
                            let name = eachExercise["name"] as! String
                            let description = eachExercise["description"] as! String
                            let id = eachExercise["id"] as! Int

                            self.fetchedExercise.append(Exercise(name: name, description: description))
                        }
                    }


                    DispatchQueue.main.async {
                        self.tableView.reloadData()
                    }
                }
            }
            catch {
                print("Error while parsing data.")
            }
        }
    }
    task.resume()
}

【问题讨论】:

  • 投到String。
  • 我之前尝试过,但没有成功,但经过几次尝试,我意识到应该怎么做。我以前很困惑,但现在它工作正常。谢谢。

标签: json swift api parsing


【解决方案1】:

使用where 子句和可选的向下转换Any 到String

for eachExercise in exercises where eachExercise["license_author"] as? String == "wger.de" { ...

【讨论】:

    【解决方案2】:

    您需要将其转换为字符串。

    if eachExercise["license_author"] as? String == "wger.de" {
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-22
      • 2015-10-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-16
      • 1970-01-01
      • 2014-09-11
      相关资源
      最近更新 更多