测试已测试 | ✗ |
语言语言 | SwiftSwift |
许可证 | MIT |
发布最新发布 | 2017年1月 |
SwiftSwift 版本 | 3.0 |
SPM支持 SPM | ✗ |
由 Simon Germain 维护。
do {
let jsonData = try Data(contentsOfURL: URL(string: url)!)
let json = try JSONSerialization.JSONObject(jsonData, options: [])
if let json = jsonOptional as? [String: Any] {
if let other = json["other"] as? [String: Any] {
if let nicknames = other["nicknames"] as? [String] {
if let handle = nicknames[0] as? String {
print("Some folks call me \(handle)")
}
}
}
}
}
catch {
print("Dangit, what happened here? \(error.localizedDescription)")
}
do {
let jsonData = try Data(contentsOfURL: URL(string: url)!)
let parser = try JSONParser(data: jsonData)
if let handle = try parser.getString("other.nicknames[0]") {
print("Some folks call me \(handle)")
}
}
catch {
print("Dangit! Another error! \(error.localizedDescription)")
}
let parser = JSONParser(dictionary: existingDictionary)
if let handle = try parser.getString("other.nicknames[0]") {
print("Some folks like to call me \(handle)")
}
我们想要解析的示例 JSON 有效负载
{
"name": "Mike",
"favorite_number": 19,
"gpa": 2.6,
"favorite_things": ["Github", 42, 98.6],
"other": {
"city": "San Francisco",
"commit_count": 9000,
"nicknames": ["mrap", "Mikee"]
}
}
获取特定类型的值。返回可选类型
if let name = try parser.getString("name") {
print("My name is \(name)")
}
if let number = try parser.getInt("favorite_number") {
print("\(number) is my favorite number!")
}
if let gpa = try parser.getDouble("gpa") {
print("My stellar highschool gpa was \(gpa)")
}
如果你想获取 Any
可以这样做
if let city = parser.get("other.city") {
// city will be type Any
}
获取值数组
if let favorites = parser.getArray("favorite_things") {
// favorites => ["Github", 42, 98.6]
}
使用新的 Swift try/catch
块,错误处理从未如此简单!
do {
let badJsonData = try Data(contentsOfURL: URL(string: url)!)
let parser = try JSONParser(data: badJsonData)
// Everything was fine past this point! Rock on!!
}
catch {
// Dangit! One more error... *sigh*
print("Some error happened! Fix it! Here it is: \(error.localizedDescription)")
}
使用 SFJSON 的最佳方法是通过 CocoaPods
Podfile
并在你的 target
部分下添加 pod 'SFJSON'
use_frameworks!
pod install
以此让 CocoaPods 下载 pod 并安装到你的项目SFJSON
import SFJSON
添加到你的 Swift 类中,然后开始使用 SFJSON
!这个框架不是我的原创想法。原始想法属于 Mike Rapadas (https://github.com/mrap),我非常感谢。他的框架本质上与本框架相同,只不过他是用 Swift 的第一个版本编写的。我只是更新了它,并使之适应 Swift 3,这是更为先进的。