Last active
August 29, 2015 14:24
-
-
Save ckeyer/a74bbf1186a60ba81cd6 to your computer and use it in GitHub Desktop.
json编码含有time.Time类型的结构体时的格式化
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" | |
"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