在我们开发中,经常会解析time.Time
往往前台传过来的时候,是个string
但是我们希望在结构体转成time.Time
type Param struct { Start time.Time `json:"start"` End time.Time `json:"end"` }
如果直接使用json.UnmarshalJSON
会失败。我们需要重写UnmarshalJSON
和MarshalJSON
方法
const ( timeFormat = "2006-01-02 15:04:05" ) type Time time.Time func (t *Time) UnmarshalJSON(data []byte) (err error) { now, err := time.ParseInLocation(`"`+timeFormat+`"`, string(data), time.Local) *t = Time(now) return } func (t *Time) MarshalJSON() ([]byte, error) { b := make([]byte, 0, len(timeFormat)+2) b = append(b, '"') b = time.Time(*t).AppendFormat(b, timeFormat) b = append(b, '"') return b, nil } func (t Time) String() string { return time.Time(t).Format(timeFormat) } func main() { p := &Param{} str := `{"start":"2019-12-10 18:12:49","end":"2019-12-10 18:12:49"}` err := json.Unmarshal([]byte(str), p) if err != nil { log.Fatal(err) } log.Println(p, str) }
如果在gin
中直接可以定义成以下格式
type Param struct { BeginTime int64 `json:"begin_time" form:"begin_time" binding:"required"` EndTime int64 `json:"end_time"form:"end_time" binding:"required" ` } var p = &Param{} ctx.ShouldBindJSON(p) ctx.ShouldBindQuery(p)