JSONMagic 在Swift中遍历和解析JSON

jopen 6年前





github "kgn/JSONMagic"


pod 'JSONMagic'


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.


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


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


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

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