Swift 中的 JSON 处理:适用于 iOS/macOS 的 Codable、Foundation 和 SwiftyJSON

面向初学者的在线Python训练器

轻松学习Python,无需理论负担。在浏览器中直接解决带自动检查的实践任务,无需安装任何东西。

开始课程

Swift 中的 JSON 处理 (iOS/macOS):完整指南



JSON (JavaScript Object Notation) 是现代应用程序中最流行的数据交换格式之一。在 Apple 生态系统(iOS、macOS、watchOS、tvOS)中,Swift 提供了几种强大的 JSON 处理方式。在本文中,我们将讨论三种主要方法:原生的 Codable、低级别的 JSONSerialization 以及流行的第三方库 SwiftyJSON。您将学习如何在 Swift 中解析、创建和处理 JSON,并附有代码示例。



1. Codable — Swift 的现代标准



从 Swift 4 开始,Apple 引入了 Codable 协议(它结合了 Encodable 和 Decodable)。这是处理 JSON 最方便且类型安全的方式。您只需声明一个符合 Codable 的结构体或类,然后使用 JSONEncoder/JSONDecoder 即可。



示例:从 API 响应中解析 JSON



import Foundation

// 定义一个自动符合 Codable 的模型struct User: Codable { let id: Int let name: String let email: String let isActive: Bool}

// 示例 JSON 字符串let jsonString = """{ "id": 42, "name": "伊万·彼得罗夫", "email": "ivan@example.com", "isActive": true}"""

// 解析if let jsonData = jsonString.data(using: .utf8) { let decoder = JSONDecoder() do { let user = try decoder.decode(User.self, from: jsonData) print("用户: \\(user.name), 邮箱: \\(user.email)") } catch { print("解码错误: \\(error.localizedDescription)") }}


示例:从对象创建 JSON



let user = User(id: 1, name: "安娜·斯米尔诺娃", email: "anna@test.com", isActive: false)let encoder = JSONEncoder()encoder.outputFormatting = .prettyPrinted // 用于美化格式

if let jsonData = try? encoder.encode(user), let jsonString = String(data: jsonData, encoding: .utf8) { print(jsonString)}


处理嵌套结构和数组



struct Company: Codable {    let name: String    let employees: [User]}

let companyJson = """{ "name": "TechCorp", "employees": [ {"id": 1, "name": "奥列格", "email": "oleg@tc.com", "isActive": true}, {"id": 2, "name": "玛丽亚", "email": "maria@tc.com", "isActive": false} ]}"""

if let data = companyJson.data(using: .utf8), let company = try? JSONDecoder().decode(Company.self, from: data) { print("公司: \\(company.name), 员工数: \\(company.employees.count)")}


2. JSONSerialization — 经典方法 (Foundation)



在 Codable 出现之前,主要工具是 Foundation 中的 JSONSerialization。它处理 Foundation 的字典和数组([String: Any] 和 [Any])。当 JSON 结构事先未知或高度动态时,此方法非常有用。



示例:使用 JSONSerialization 解析



if let data = jsonString.data(using: .utf8) {    do {        if let dict = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {            let id = dict["id"] as? Int ?? 0            let name = dict["name"] as? String ?? "未知"            print("ID: \\(id), 姓名: \\(name)")        }    } catch {        print("错误: \\(error)")    }}


缺点:缺乏类型安全性——需要手动进行类型转换,这可能导致运行时错误。建议尽可能使用 Codable。



3. SwiftyJSON — 便捷的第三方库



SwiftyJSON 是一个流行的开源库,它简化了 Swift 中的 JSON 处理。它提供了一种更简洁的语法来访问 JSON 值,并减少了强制转换的需要。

推荐