Skip to content

Commit

Permalink
Added README documentation for directly unboxing keyPaths to the
Browse files Browse the repository at this point in the history
  • Loading branch information
clayellis committed Jul 20, 2016
1 parent 2b85637 commit 368bf11
Showing 1 changed file with 54 additions and 2 deletions.
56 changes: 54 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -233,7 +233,7 @@ You can also use key paths (for both dictionary keys and array indexes) to unbox

```json
{
"name": "John",
"name": "John",
"age": 27,
"activities": {
"running": {
Expand All @@ -249,12 +249,14 @@ You can also use key paths (for both dictionary keys and array indexes) to unbox
```

```swift
struct User: Unboxable {
struct User {
let name: String
let age: Int
let runningDistance: Int
let primaryDeviceName: String
}

extension User: Unboxable {
init(unboxer: Unboxer) {
self.name = unboxer.unbox("name")
self.age = unboxer.unbox("age")
Expand All @@ -264,6 +266,56 @@ struct User: Unboxable {
}
```

You can also use key paths to directly unbox nested JSON structures. This is useful when you only need to extract a specific object (or objects) out of the JSON body.

```json
{
"company": {
"name": "Spotify",
},
"jobOpenings": [
{
"title": "Swift Developer",
"salary": 120000
},
{
"title": "UI Designer",
"salary": 100000
},
]
}
```

```swift
struct JobOpening {
let title: String
let salary: Int
}

extension JobOpening: Unboxable {
init(unboxer: Unboxer) {
self.title = unboxer.unbox("title")
self.salary = unboxer.unbox("salary")
}
}

struct Company {
let name: String
}

extension Company: Unboxable {
init(unboxer: Unboxer) {
self.name = unboxer.unbox("name")
}
}
```

```
let company: Company = try Unbox(json, at: "company")
let jobOpenings: [JobOpening] = try Unbox(json, at: "jobOpenings")
let featuredOpening: JobOpening = try Unbox(json, at: "jobOpenings.0")
```

### Custom unboxing

Sometimes you need more fine grained control over the decoding process, and even though Unbox was designed for simplicity, it also features a powerful custom unboxing API that enables you to take control of how an object gets unboxed. This comes very much in handy when using Unbox together with Core Data, when using dependency injection, or when aggregating data from multiple sources. Here's an example:
Expand Down

0 comments on commit 368bf11

Please sign in to comment.