我是 JSON 世界的新手。我刚刚开始在 Swift 中使用 JSON。
现在,我有以下功能:
func forShow() {
// Using ACORN API to fetch the course codes
guard let url[enter image description here][1]Online = URL(string: "https://timetable.iit.artsci.utoronto.ca/api/20179/courses?code=CSC") else { return }
let session = URLSession.shared
session.dataTask(with: urlOnline) { (data, response, error) in
if let response = response {
print(response)
}
if let data = data {
print(data)
do {
let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers)
print(json)
} catch {
print(error)
}
}
}.resume()
}
我收到的回复是所有类(class)的代码字符串中都包含“CSC”。我想根据响应形成一个包含所有完整类(class)代码的数组。我将在这里粘贴一门类(class)的回复:
所以,我想访问图像中看到的所有类(class)代码。我希望能够访问“CSC104H1-F-20179”。
最佳答案
将 JSON 视为字典。您在顶层拥有所有类(class)名称,因此幸运的是您不必深入挖掘层次结构。
那么,你有:
let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers)
print(json)
更改为:
if let arrayOfCourses = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [[String: Any]] {
for (course, _) in arrayOfCourses {
print(course)
}
}
关于ios - Swift - 从 JSON 响应形成数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47319548/