Last active
April 16, 2018 16:08
-
-
Save bylatt/deab06fef5fc6758ffb308e475d05674 to your computer and use it in GitHub Desktop.
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
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