Last active
March 26, 2019 02:21
-
-
Save peacefixation/d0cb355a7bd9ee342ee980e6d9160e2c to your computer and use it in GitHub Desktop.
Implement MarshalJSON and UnmarshalJSON on a custom type
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import ( | |
"fmt" | |
"strings" | |
"time" | |
) | |
const timeFormat = "2006-01-02 15:04:05" | |
// JSONTime a wrapper for time.Time that unmarshalls with a custom date format | |
type JSONTime struct { | |
time.Time // anonymous field, struct inherits methods, refer to instance.Time | |
} | |
// UnmarshalJSON unmarshal JSON field to a JSONTime | |
func (t *JSONTime) UnmarshalJSON(buf []byte) error { | |
tt, err := time.Parse(timeFormat, strings.Trim(string(buf), `"`)) | |
if err != nil { | |
return err | |
} | |
t.Time = tt | |
return nil | |
} | |
// MarshalJSON marshal JSONTime to a JSON field | |
func (t *JSONTime) MarshalJSON() ([]byte, error) { | |
formatted := fmt.Sprintf("\"%s\"", t.Time.Format(timeFormat)) | |
return []byte(formatted), nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment