time.Time
package main
import (
"encoding/json"
"os"
"time"
)
type MyStruct struct {
ID uint `json:"id"`
Name string `json:"name"`
CreatedAt time.Time `json:"created_at"`
}
func main() {
_ = json.NewEncoder(os.Stdout).Encode(
&MyStruct{1, "Xander", time.Now()},
)
}
输出:
{"id":1,"name":"Xander","created_at":"2021-04-13T20:38:51.466566+08:00"}
2006-01-02 15:04:05
MyStructMarshalJSON
func (m *MyStruct) MarshalJSON() ([]byte, error) {
type Alias MyStruct
return json.Marshal(&struct {
*Alias
CreatedAt string `json:"created_at"`
}{
Alias: (*Alias)(m),
CreatedAt: m.CreatedAt.Format("2006-01-02 15:04:05"),
})
}
输出:
{"id":1,"name":"Xander","created_at":"2021-04-13 20:45:26"}
MarshalJSON
但后续代码中用起来稍微麻烦点
type JSONTime time.Time
// 或者
type JSONTime struct {
time.Time
}
如:
type JSONTime time.Time
func (t JSONTime)MarshalJSON() ([]byte, error) {
//do your serializing here
stamp := fmt.Sprintf("\"%s\"", time.Time(t).Format("2006-01-02 15:04:05"))
return []byte(stamp), nil
}