5. Inthe beginning...
if let id = json["id"] as? Int {
if let name = json["name"] as? String {
if let email = json["email"] as? String {
// create user
}
}
}
6. Swift 1.2
if let id = json["id"] as? Int,
name = json["name"] as? String,
email = json["email"] as? String {
// create user
}
else {
// return some error, ex: `Result<T>`
}
7. Swift 2
guard let id = json["id"] as? Int,
name = json["name"] as? String,
email = json["email"] as? String {
// throw some error
}
// create user
8. Argo
extension User: Decodable {
static func decode(j: JSON) -> Decoded<User> {
return curry(User.init) // used to have to make a separate `make` function
<^> j <| "id"
<*> j <| "name"
<*> j <|? "email" // Use ? for parsing optional values
<*> j <| "role" // Custom types that also conform to Decodable just work
<*> j <| ["company", "name"] // Parse nested objects
<*> j <|| "friends" // parse arrays of objects
}
}
(https://github.com/thoughtbot/Argo)
13. JSONArrays...
var pets = [Pet]()
if let petsObjects = json["pets"] as? [JSONObject] {
for petObject in petsObjects {
guard let id = petObject["id"] as? Int,
name = petObject["name"] as? String else {
continue // or throw error if less tolerant
}
let pet = Pet(id: id, name: name)
pets.append(pet)
}
}
18. Caveat: Core DataModels
For NSManagedObject subclasses JSONObjectConvertible
won't really work because init is not so simple...
public protocol JSONDecoding {
func update(json: JSONObject) throws
}
19. Caveat: Core DataModels
class User: NSManagedObject, JSONDecoding {
@NSManaged var name: String
@NSManaged var email: String
func update(json: JSONObject) throws {
try name = json.valueForKey("name")
try email = json.valueForKey("email")
}
}
22. Resources
» My blog jasonlarsen.me (look for No-Magic JSON
series)
» JaSON https://github.com/jarsen/JaSON
» JaSON (extension on Dictionary) https://
github.com/bwhiteley/JaSON