Swift 2017-05-19 11:09
Swift JSON 解析类 Unbox
回复:0 查看:6272 感兴趣:29 赞:4
简单易用的Swift JSON 解析类 Unbox。
示例代码:
示例代码:
//JSON数据 { "name": "John", "age": 27 } //结构体User struct User { let name: String let age: Int } //User扩展Unboxable extension User: Unboxable { init(unboxer: Unboxer) throws { self.name = try unboxer.unbox(key: "name") self.age = try unboxer.unbox(key: "age") } } //解析 let user: User = try unbox(dictionary: dictionary) //或 let user: User = try unbox(data: data)指定KeyPath:
//JSON格式 { "name": "John", "age": 27, "activities": { "running": { "distance": 300 } }, "devices": [ "Macbook Pro", "iPhone", "iPad" ] } struct User { let name: String let age: Int let runningDistance: Int let primaryDeviceName: String } extension User: Unboxable { init(unboxer: Unboxer) throws { self.name = try unboxer.unbox(key: "name") self.age = try unboxer.unbox(key: "age") //下面两行指定keyPath self.runningDistance = try unboxer.unbox(keyPath: "activities.running.distance") self.primaryDeviceName = try unboxer.unbox(keyPath: "devices.0") } }
相关开源代码
EFIconFont: 一个用 Swift 实现的 IconFont 封装
Swift Zip文件压缩与解压框架
EFResume - 一个普通的 Swift 简历模板
Swift 优雅的定时器及执行工具库 Each
Swift 解析、格式化及验证国际电话号码工具库 PhoneNumberKit
Swift 版 FlatBuffers(跨平台序列化库)FlatBuffersSwift
Swift 编写的 Github API 客户端 Github.swift
Swift OAuth授权库 SwiftyOAuth
Swift 音频处理库 TempiFFT
iOS通知中心封装库SwiftNotificationCenter