SFJSON 1.0.0

SFJSON 1.0.0

测试已测试
语言语言 SwiftSwift
许可证 MIT
发布最新发布2017年1月
SwiftSwift 版本3.0
SPM支持 SPM

Simon Germain 维护。



SFJSON 1.0.0

  • Simon Germain

使用路径解析 JSON!

这很糟糕

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)")
}

你的 JSON 已经解析?没问题!

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

  1. 打开你的 Podfile 并在你的 target 部分下添加 pod 'SFJSON'
  2. 确保存在 use_frameworks!
  3. 运行 pod install 以此让 CocoaPods 下载 pod 并安装到你的项目
  4. 确保在安装 pod 之后编译一次你的项目,以便项目可以引用 SFJSON
  5. import SFJSON 添加到你的 Swift 类中,然后开始使用 SFJSON

免责声明

这个框架不是我的原创想法。原始想法属于 Mike Rapadas (https://github.com/mrap),我非常感谢。他的框架本质上与本框架相同,只不过他是用 Swift 的第一个版本编写的。我只是更新了它,并使之适应 Swift 3,这是更为先进的。