gpt4 book ai didi

json - 在swift中过滤JSON数据

转载 作者:行者123 更新时间:2023-11-30 11:58:45 24 4
gpt4 key购买 nike

我正在尝试解析我的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com