Skip to content

Commit

Permalink
Added README to explain how to support custom types (#149) (#150)
Browse files Browse the repository at this point in the history
* Added README to explain how to support custom types (#149)

* Fix incorrect docstring
  • Loading branch information
sjauld authored and aren55555 committed Aug 21, 2018
1 parent 5d047c6 commit 3b9f84a
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -343,6 +343,37 @@ func (post Post) JSONAPIRelationshipMeta(relation string) *Meta {
}
```

### Custom types

If you need to support custom types (e.g. for custom time formats), you'll need to implement the json.Marshaler and json.Unmarshaler interfaces on the type.

```go
// MyTimeFormat is a custom format I invented for fun
const MyTimeFormat = "The time is 15:04:05. The year is 2006, and it is day 2 of January."

// MyTime is a custom type used to handle the custom time format
type MyTime struct {
time.Time
}

// UnmarshalJSON to implement the json.Unmarshaler interface
func (m *MyTime) UnmarshalJSON(b []byte) error {
t, err := time.Parse(MyTimeFormat, string(b))
if err != nil {
return err
}

m.Time = t

return nil
}

// MarshalJSON to implement the json.Marshaler interface
func (m *MyTime) MarshalJSON() ([]byte, error) {
return json.Marshal(m.Time.Format(MyTimeFormat))
}
```

### Errors
This package also implements support for JSON API compatible `errors` payloads using the following types.

Expand Down

0 comments on commit 3b9f84a

Please sign in to comment.