Last active
August 29, 2015 14:06
-
-
Save hkurokawa/16ae6be239e8587848a2 to your computer and use it in GitHub Desktop.
Serialize/Deserialize time.Time to/from JSON
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
// This code snippet demonstrates how to serialize/deserialize a struct | |
// who has one or more date fields to/from JSON. | |
// | |
// Though, this example implements both encoding.TextMarshaler and json.JSONMarshaler, | |
// either is necessary to format/parse time.Time in JSON format. | |
package main | |
import ( | |
"encoding/json" | |
"fmt" | |
"time" | |
) | |
type LastLogin struct { | |
Login string `json:"login"` | |
IP string `json:"ip"` | |
CreatedAt jsonTime `json:"created_at"` | |
} | |
type jsonTime struct { | |
t time.Time | |
} | |
func (j jsonTime) String() string { | |
return j.t.String() | |
} | |
func (j jsonTime) MarshalText() ([]byte, error) { | |
return []byte(j.t.Format("2006-01-02 15:04:05")), nil | |
} | |
func (t *jsonTime) UnmarshalText(data []byte) (err error) { | |
(*t).t, err = time.Parse("2006-01-02 15:04:05", string(data)) | |
return err | |
} | |
func (j jsonTime) MarshalJSON() ([]byte, error) { | |
return []byte(j.t.Format("\"2006-01-02 15:04:05\"")), nil | |
} | |
func (t *jsonTime) UnmarshalJSON(data []byte) (err error) { | |
(*t).t, err = time.Parse("\"2006-01-02 15:04:05\"", string(data)) | |
return err | |
} | |
func main() { | |
fmt.Println("Hello, playground") | |
str := "{\"ip\": \"127.250.0.168\", \"login\": \"bernardo_stracke\", \"created_at\": \"2014-02-24 05:53:26\"}" | |
ll := &LastLogin{} | |
json.Unmarshal([]byte(str), ll) | |
fmt.Printf("%v\n", *ll) | |
js, _ := json.Marshal(*ll) | |
fmt.Printf("%v\n", string(js)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment