Last active
May 6, 2019 06:20
-
-
Save panxue/da700af44ad8620c73f90a8c676d56f7 to your computer and use it in GitHub Desktop.
自定义json输出
This file contains hidden or 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 ( | |
| "bytes" | |
| "encoding/json" | |
| "fmt" | |
| "strconv" | |
| "time" | |
| ) | |
| // Person : for test struct | |
| type Person struct { | |
| Birthday *JavaTime `json:"birthday"` | |
| } | |
| func main() { | |
| bir := JavaTime(time.Date(1991, time.August, 01, 0, 0, 0, 0, time.UTC)) | |
| p := Person{Birthday: &bir} | |
| // 从类型转换为 json 字符串: | |
| j, _ := json.Marshal(p) | |
| fmt.Printf("json := %v\n", string(j)) | |
| // 从 json 字符串,转换为 类型: | |
| json.Unmarshal(j, &p) | |
| bir = *p.Birthday | |
| golangTime := time.Time(bir) | |
| fmt.Printf("bir year = %v\n", golangTime.Year()) | |
| } | |
| // JavaTime : time.Time | |
| type JavaTime time.Time | |
| // UnmarshalJSON : UnmarshalJSON 自定义从json->转换器 | |
| func (j *JavaTime) UnmarshalJSON(data []byte) error { | |
| millis, err := strconv.ParseInt(string(data), 10, 64) | |
| if err != nil { | |
| return err | |
| } | |
| *j = JavaTime(time.Unix(0, millis*int64(time.Millisecond))) | |
| return nil | |
| } | |
| // MarshalJSON : 自定义对象转换到 json | |
| func (j *JavaTime) MarshalJSON() (data []byte, err error) { | |
| var buf bytes.Buffer | |
| origin := time.Time(*j) | |
| buf.WriteString(strconv.FormatInt(origin.UnixNano()/int64(time.Millisecond), 10)) | |
| return buf.Bytes(), nil | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment