Arrow
identifier <-- json["id"]
name <-- json["name"]
stats <-- json["stats"]
因为 Swift 中解析 JSON 总是充满 不必要的 if 语句,显然的类型转换和 nil 检查
一定有更好的方法
试试它
Arrow 是 freshOS iOS 工具集的一部分。在一个示例 App 中尝试它! 下载启动项目
如何使用
通过使用一个简单的箭头操作符,它可以为我们处理样板代码。
Json 映射代码变得更 简洁 且 易于维护
为什么使用 Arrow
- 推断类型
- 使模型保持整洁
- 处理自定义和嵌套模型
- 点和对齐语法
- 纯Swift,简单且轻量
示例
Swift 模型
struct Profile {
var identifier = 0
var name = ""
var link:NSURL?
var weekday:WeekDay = .Monday
var stats = Stats()
var phoneNumbers = [PhoneNumber]()
}
JSON 文件
{
"id": 15678,
"name": "John Doe",
"link": "https://apple.com/steve",
"weekdayInt" : 3,
"stats": {
"numberOfFriends": 163,
"numberOfFans": 10987
},
"phoneNumbers": [{
"label": "house",
"number": "9809876545"
}, {
"label": "cell",
"number": "0908070656"
}, {
"label": "work",
"number": "0916570656"
}]
}
(混乱之前)
var profile = Profile()
// Int
if let id = json["id"] as? Int {
profile.identifier = id
}
// String
if let name = json["name"] as? String {
profile.name = name
}
// NSURL
if let link = json["link"] as? String, url = NSURL(string:link) {
profile.link = link
}
// Enum
if let weekdayInt = json["weekdayInt"] as? Int, weekday = WeekDay(rawValue:weekdayInt) {
profile.weekday = weekday
}
// Custom nested object
if let statsJson = json["stats"] as? AnyObject {
if let numberOfFans = statsJson["numberOfFans"] as? Int {
profile.stats.numberOfFans = numberOfFans
}
if let numberOfFriends = statsJson["numberOfFriends"] as? Int {
profile.stats.numberOfFriends = numberOfFriends
}
}
// Array of custom nested object
if let pns = json["phoneNumbers"] as? [AnyObject] {
for pn in pns {
phoneNumbers.append(PhoneNumber(json: pn))
}
}
🎉 🎉 🎉
之后extension Profile:ArrowParsable {
mutating func deserialize(json: JSON) {
identifier <-- json["id"]
link <-- json["link"]
name <-- json["name"]
weekday <-- json["weekdayInt"]
stats <- json["stats"]
phoneNumbers <-- json["phoneNumbers"]
}
}
使用方法
let profile = Profile()
profile.deserialize(json)
安装
Carthage
github "freshOS/Arrow"
CocoaPods
target 'MyApp'
pod 'Arrow'
use_frameworks!
手动操作
简单复制粘贴 Xcode 项目中的 .swift
文件 :)
作为一个框架
克隆此仓库,并在示例项目中构建 Framework 目标。然后链接到此框架。
这怎么工作
注意之前我们输入了
stats <-- json["stats"]
这是因为我们创建了一个名为 "Stats+Arrow.swift" 的扩展,使得我们能够使用箭头操作符
// Stats+Arrow.swift
import Foundation
extension Stats:ArrowParsable {
mutating func deserialize(json: JSON) {
numberOfFriends <-- json["numberOfFriends"]
numberOfFans <-- json["numberOfFans"]
}
}
你说的灵活
- 我是否必须为我的子模型使用 <-- ?
- 不需要,如果你想这样写也可以
stats.numberOfFriends <-- json["stats.numberOfFriends"]
stats.numberOfFans <-- json["stats.numberOfFans"]
日期解析
全局
// Configure Global Date Parsing with one of those
Arrow.setDateFormat("yyyy-MM-dd'T'HH:mm:ssZZZZZ")
Arrow.setUseTimeIntervalSinceReferenceDate(true)
Arrow.setDateFormatter(aDateFormatter)
// Then later dates can be parsed form custom date format or timestamps automatically 🎉
let json:JSON = JSON(["date": "2013-06-07T16:38:40+02:00", "timestamp": 392308720])
date1 <-- json["date"]
date2 <-- json["timestamp"]
按键基于
createdAt <-- json["created_at"]?.dateFormat("yyyy-MM-dd'T'HH:mm:ssZZZZZ")
createdAt <-- json["created_at"]?.dateFormatter(aCustomDateFormatter)
只需根据每个案例提供即可!
访问JSON值
嵌套值
value <-- json["nested.nested.nested.nestedValue"]
索引处的对象
value <-- json[12]
合并两者
value <-- json[1]?["someKey"]?[2]?["something.other"]
在数组上循环
if let collection = json.collection {
for jsonEntry in collection {
//Do something
}
}
Swift 版本
- Swift 2 -> 版本 2.0.3
- Swift 3 -> 版本 3.0.5
- Swift 4 -> 版本 4.0.0
- Swift 4.1 -> 版本 4.1.0
- Swift 4.2 -> 版本 4.2.0
- Swift 5.0 -> 版本 5.0.0
- Swift 5.1 -> 版本 5.1.0
- Swift 5.1.3 -> 版本 5.1.1
致谢
本项目离不开YannickDot、Damien-nd和maxkonovalov的贡献。
<script async defer src="https://buttons.github.io/buttons.js"></script>赞助者
喜欢这个项目吗?提供咖啡或通过月度捐赠支持我们,帮助我们继续活动:
赞助商
成为赞助商并在我们GitHub的README上放置您的标志,附带连接到您网站的链接: