Files
Argo/Documentation/Decode-Root-Keys.md
Gordon Fontenot 40ca612fcb Use JSON.init instead of JSON.parse
Previously, we were using a static func here because we needed to
recursively pass it during initial parsing. However, since we can now
pass the initializer, I think it makes sense to simplify the API by
directly using an initializer.
2016-04-05 14:38:57 -05:00

790 B

Decoding with Root Keys

The easiest way to decode models from JSON is to use the global decode function: pass the AnyObject variable returned from NSJSONSerialization directly to decode, and you'll get the model back. However, many times the JSON for the model is embedded within a root key:

{
  "user": {
    "id": 1881372911,
    "name": "George Senior"
  }
}

In this case, you can't use the global decode function because it assumes the object you're trying to decode is at the root level. To get around this, first transform the AnyObject into a JSON type, then use the <| operator to pull out the object and decode it into its model.

let json = JSON(anyObject)

let user: Decoded<User> = json <| "user"
// or
let user: User? = json <| "user"