【问题标题】:Swift - Forming an array from a JSON ResponseSwift - 从 JSON 响应中形成一个数组
【发布时间】:2017-11-16 00:22:33
【问题描述】:

我是 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()
}

我收到所有课程在其代码字符串中包含“CSC”的回复。我想根据响应形成一个包含所有完整课程代码的数组。我将在此处粘贴一门课程的回复:

所以,我想访问图片中看到的所有课程代码。我希望能够访问的是“CSC104H1-F-20179”。

【问题讨论】:

标签: ios json swift get


【解决方案1】:

将您的 JSON 视为字典。您拥有顶层的所有课程名称,所以幸运的是您不必深入挖掘层次结构。

那么,你在哪里:
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) } }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多