CocoaPods trunk is moving to be read-only. Read more on the blog, there are 14 months to go.
| TestsTested | ✓ |
| LangLanguage | SwiftSwift |
| License | MIT |
| ReleasedLast Release | Oct 2016 |
| SPMSupports SPM | ✗ |
Maintained by David Keegan.
JSONMagic makes it easy to traverse and parse JSON in Swift.
Lets say you get a JSON user profile like this from your server:
{
"user": {
"name": "David Keegan",
"age": 30,
"accounts": [
{
"name": "twitter",
"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 twitterUser: String?
if let data = serverResponse {
if let json = try? NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String: Any] {
if let user = json?["user"] as? [String: Any] {
if let accounts = user["accounts"] as? [Any] {
if let twitter = accounts.first as? [String: Any] {
twitterUser = twitter["user"] as? String
}
}
}
}
}let twitterUser = JSONMagic(data: serverResponse).get("user").get("accounts").first.get("user").stringOr, if you prefer subscripting :)
let twitterUser = JSONMagic(data: serverResponse)["user"]["accounts"][0]["user"].stringIt even works with Paw key paths.
let twitterUser = JSONMagic(data: serverResponse).keypath("user.accounts.0.user").stringJSONMagic 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. There are helpers for all the JSON data types too: .bool, .int, .float, .double, .string, .array and .dictionary.
It’s super loosie goosie so doesn’t care about nil values going in, or anywhere in the chain.
let json = JSONMagic(data: serverResponse)
json.get("user").get("name").string // David Keegan
json["user"]["age"].integer // 30
let twitter = json.get("user").get("accounts").first
twitter["name"].value // twitter
twitter["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