ios - Swift - 从 JSON 响应形成数组

标签 ios json swift get

我是 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)的回复:

enter image description here

所以,我想访问图像中看到的所有类(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/

相关文章:

ios - XCode 5.1 强制对 Cocos2d-iphone v3 项目进行 32 位编译

javascript - 将返回的 JSON 对象属性转换为(较低的第一个)camelCase

ios - 无法快速获取 View Controller 的索引,该 View Controller 是 UINavigationController 的 View Controller

ios - 启动时自定义 View Controller

ios - 如何将 Realm 对象类添加到 RLMArray

javascript - Angular ng-repeat动态对象数组

json - 如何根据丰富进行动态调度?

ios - 泛型 Obj-c 的 Swift 3 扩展无法访问类的泛型参数

ios - AVAudioSession.sharedInstance 没有被调用

ios - 图像选择器委托(delegate)错误 : cannot assign value of type