Skip to content

Instantly share code, notes, and snippets.

@ckeyer
Last active August 29, 2015 14:24
Show Gist options
  • Save ckeyer/a74bbf1186a60ba81cd6 to your computer and use it in GitHub Desktop.
Save ckeyer/a74bbf1186a60ba81cd6 to your computer and use it in GitHub Desktop.
json编码含有time.Time类型的结构体时的格式化
package main
import (
"encoding/json"
"fmt"
"time"
)
type JsonTime struct {
time.Time
}
func (this JsonTime) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf("%d", this.Year())), nil
}
type Person struct {
Name string
Birth JsonTime
}
func main() {
p := &Person{
Name: "hahah",
Birth: JsonTime{time.Now()},
}
fmt.Println(p.Birth)
b, e := json.Marshal(p)
if e != nil {
fmt.Println(e)
}
fmt.Printf("%s\n", b)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment