| 注册
请输入搜索内容

热门搜索

Java Linux MySQL PHP JavaScript Hibernate jQuery Nginx
jopen
9年前发布

JSONMagic 在Swift中遍历和解析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 自行上传分享,仅供网友学习交流。所有权归原作者,若您的权利被侵害,请联系管理员。
 转载本站原创文章,请注明出处,并保留原始链接、图片水印。
 本站是一个以用户分享为主的开源技术平台,欢迎各类分享!
 本文地址:https://www.open-open.com/lib/view/open1456046336667.html
JSON开发包