Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import (
- "encoding/json"
- "fmt"
- "strings"
- "time"
- )
- const messageTimeLayout = "2006/01/02 15:04:05 -0700"
- type MessageTime struct {
- time.Time
- }
- func (mt MessageTime) MarshalJSON() ([]byte, error) {
- return []byte(fmt.Sprintf(`"%s"`, mt.Time.Format(messageTimeLayout))), nil
- }
- func (mt *MessageTime) UnmarshalJSON(b []byte) (err error) {
- s := strings.Trim(string(b), `"`)
- if s == "" || s == "null" {
- mt.Time = time.Time{}
- } else {
- mt.Time, err = time.Parse(messageTimeLayout, s)
- }
- return
- }
- func (mt MessageTime) String() string {
- return fmt.Sprintf(`"%s"`, mt.Time.Format(messageTimeLayout))
- }
- type Message struct {
- Text string `json:"text"`
- CreatedAt MessageTime `json:"created_at"`
- }
- func main() {
- rawJSON := `{"text":"Hello","created_at":"2018/04/16 23:30:00 +0700"}`
- message := Message{}
- json.Unmarshal([]byte(rawJSON), &message)
- toJSON, _ := json.Marshal(message)
- fmt.Println(string(toJSON))
- }
- // Output: {"text":"Hello","created_at":"2018/04/16 23:30:00 +0700"}
Add Comment
Please, Sign In to add comment