Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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"}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment