json - 在swift中过滤JSON数据

标签 json swift api parsing

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

但是我在网上遇到错误:

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

二元运算符“==”不能应用于“Any?”类型的操作数和“字符串”。 不过,我仍然希望将其保留为 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()
}

最佳答案

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

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

关于json - 在swift中过滤JSON数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47488842/

相关文章:

ios - 我可以在 AudioKit 中设置 bufferLength 而不是 2 的幂吗?

javascript - 有没有办法让我可以制作一个 chrome 扩展程序,在按下时使用其 API 在计算机上打开另一个应用程序

php - 未捕获的语法错误意外数字 JSON.parse

java - java中将json对象转换为tsv格式

ios - UIBezierPath 围绕 UIView 的中心旋转

swift - 尝试快速捕获变量

javascript - 在 javascript 中使用 python 输出

api - 如何热链接/嵌入 Twitpic 图像?

javascript - 从ajax调用ajax函数

ios - 带有嵌套数据的 Swift 4 JSON 解码器