Skip to content

Instantly share code, notes, and snippets.

@sinmetal
Created August 13, 2015 06:45
Show Gist options
  • Save sinmetal/6bdd9a526d21ddff926f to your computer and use it in GitHub Desktop.
Save sinmetal/6bdd9a526d21ddff926f to your computer and use it in GitHub Desktop.
EpochTimeで入っているjsonをstructに読み込むためのサンプル
package main
import (
"encoding/json"
"fmt"
"strconv"
"time"
)
type Hoge struct {
At *EpochTime `json:"at"`
}
type EpochTime time.Time
func (t *EpochTime) UnmarshalJSON(buf []byte) error {
value, err := strconv.ParseInt(string(buf), 10, 64)
if err != nil {
return err
}
*t = EpochTime(time.Unix(value, 0))
return nil
}
func (t *EpochTime) MarshalJSON() ([]byte, error) {
epoch := (time.Time)(*t).Unix()
bs := []byte(strconv.FormatInt(epoch, 10))
return bs, nil
}
func (t *EpochTime) String() string {
return (time.Time)(*t).String()
}
func main() {
var hoge Hoge
err := json.Unmarshal([]byte("{\"at\": 1437999924}"), &hoge)
if err != nil {
fmt.Println(err.Error())
}
fmt.Println(hoge.At)
buf, err := json.Marshal(&hoge)
if err != nil {
fmt.Println(err.Error())
}
fmt.Println(string(buf))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment