自定义一个 日期类型 DateTime 然后实现 Marshaler 接口的 MarshalJSON() 方法
代码语言:javascript复制package main
import (
"encoding/json"
"fmt"
"time"
)
type DateTime time.Time
func (d DateTime) MarshalJSON() ([]byte, error) {
dateTime := fmt.Sprintf("%q", time.Time(d).Format("2006-01-02 15:04:05"))
return []byte(dateTime), nil
}
type Tom struct {
Name string `json:"name"`
Age int `json:"age"`
Birthday DateTime `json:"birthday"`
}
func main() {
tom := Tom{
Name: "tom",
Age: 25,
Birthday: DateTime(time.Now()),
}
bytes, err := json.Marshal(tom)
if err == nil {
fmt.Println(string(bytes))
}
}
结果为
代码语言:javascript复制{"name":"tom","age":25,"birthday":"2021-06-18 15:04:03"}