JSONMagic 在Swift中遍歷和解析JSON

jopen 8年前發布 | 36K 次閱讀 JSON開發包

JSONMagic

JSONMagic能夠很方便地中在Swift中遍歷和解析JSON

Installing

Carthage

github "kgn/JSONMagic"

CocoaPods

pod 'JSONMagic'

Examples

Lets say you get a JSON user profile like this from your server:

{
    "user": {
        "name": "David Keegan",
        "age": 30,
        "accounts": [
            {
                "name": "推ter",
                "user": "iamkgn"
            },
            {
                "name": "dribbble",
                "user": "kgn"
            },
            {
                "name": "github",
                "user": "kgn"
            }
        ]
    }
}

Parsing this can take a bunch of nested if statements in Swift to cast things to the right type in order to traverse down the data tree.

Before

let 推terUser: String?
if let data = serverResponse {
    if let json = try? NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String: AnyObject] {
        if let user = json?["user"] as? [String: AnyObject] {
            if let accounts = user["accounts"] as? [AnyObject] {
                if let 推ter = accounts.first as? [String: AnyObject] {
                    推terUser = 推ter["user"] as? String
                }
            }
        }
    }
}

After

let 推terUser = JSONMagic(data: serverResponse).get("user").get("accounts").first.get("user").value as? String

Or, if you prefer subscripting :)

let 推terUser = JSONMagic(data: serverResponse)["user"]["accounts"][0]["user"].value as? String

JSONMagic handles all of this for you with method chaining. So you’re always working with a magical wrapper JSONMagic object that you can chain as long as you want, then just call value at the end to get the ending value and cast that to the final type you want.

It’s super loosie goosie so doesn’t care about nil values going in, or anywhere in the chain.

Some more examples

let json = JSONMagic(data: serverResponse)

json.get("user").get("name").value // David Keegan
json["user"]["age"].value // 30

let 推ter = json.get("user").get("accounts").first
推ter["name"].value // 推ter
推ter["user"].value // iamkgn

let dribbble = json.get("user").get("accounts").get(1)
dribbble.get("name").value // dribbble
dribbble.get("user").value // kgn

let github = json.get("user").get("accounts").last
github.get("name").value // github
github.get("user").value // kgn

let bad = json.get("user").get("accounts").get(5)
bad.get("name").value // nil
bad.get("user").value // nil

Progress

  • Badges
  • Tests
  • Travis
  • Carthage
  • CocoaPods
  • Description
  • Documentation

項目地址: https://github.com/kgn/JSONMagic

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!