Skip to content

Commit 3b9f84a

Browse files
sjauldaren55555
authored andcommitted
Added README to explain how to support custom types (#149) (#150)
* Added README to explain how to support custom types (#149) * Fix incorrect docstring
1 parent 5d047c6 commit 3b9f84a

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

README.md

+31
Original file line numberDiff line numberDiff line change
@@ -343,6 +343,37 @@ func (post Post) JSONAPIRelationshipMeta(relation string) *Meta {
343343
}
344344
```
345345

346+
### Custom types
347+
348+
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.
349+
350+
```go
351+
// MyTimeFormat is a custom format I invented for fun
352+
const MyTimeFormat = "The time is 15:04:05. The year is 2006, and it is day 2 of January."
353+
354+
// MyTime is a custom type used to handle the custom time format
355+
type MyTime struct {
356+
time.Time
357+
}
358+
359+
// UnmarshalJSON to implement the json.Unmarshaler interface
360+
func (m *MyTime) UnmarshalJSON(b []byte) error {
361+
t, err := time.Parse(MyTimeFormat, string(b))
362+
if err != nil {
363+
return err
364+
}
365+
366+
m.Time = t
367+
368+
return nil
369+
}
370+
371+
// MarshalJSON to implement the json.Marshaler interface
372+
func (m *MyTime) MarshalJSON() ([]byte, error) {
373+
return json.Marshal(m.Time.Format(MyTimeFormat))
374+
}
375+
```
376+
346377
### Errors
347378
This package also implements support for JSON API compatible `errors` payloads using the following types.
348379

0 commit comments

Comments
 (0)