Created
August 13, 2015 06:45
-
-
Save sinmetal/6bdd9a526d21ddff926f to your computer and use it in GitHub Desktop.
EpochTimeで入っているjsonをstructに読み込むためのサンプル
This file contains 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" | |
"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