用Gin框架遇到的问题,如果前端用json传了"seven_expiry": "2020-05-08"而后端SevenExpiry的类型是time.Time的话,怎么去获取这个值呢?我试了直接ShouldBindJSON这个方法报错parsing time ""2020-05-08"" as ""2006-01-02T15:04:05Z07:00"": cannot parse """ as "T"
gin用的官方json解析库,官方实现是在Time类型实现的json.Unmarshaler接口。
```
const (
RFC3339 = "2006-01-02T15:04:05Z07:00"
RFC3339Nano = "2006-01-02T15:04:05.999999999Z07:00"
)
// MarshalJSON implements the json.Marshaler interface.
// The time is a quoted string in RFC 3339 format, with sub-second precision added if present.
func (t Time) MarshalJSON() ([]byte, error) {
if y := t.Year(); y < 0 || y >= 10000 {
// RFC 3339 is clear that years are 4 digits exactly.
// See golang.org/issue/4556#c15 for more discussion.
return nil, errors.New("Time.MarshalJSON: year outside of range [0,9999]")
}
b := make([]byte, 0, len(RFC3339Nano)+2)
b = append(b, '"')
b = t.AppendFormat(b, RFC3339Nano)
b = append(b, '"')
return b, nil
}
// UnmarshalJSON implements the json.Unmarshaler interface.
// The time is expected to be a quoted string in RFC 3339 format.
func (t *Time) UnmarshalJSON(data []byte) error {
// Ignore null, like in the main JSON package.
if string(data) == "null" {
return nil
}
// Fractional seconds are handled implicitly by Parse.
var err error
*t, err = Parse(`"`+RFC3339+`"`, string(data))
return err
}
```
很明显是写死的,没有预留给外部改的入口。
你只能把Time再type定义成了一个其它类型,或者用struct包装一下,再重新实现json.Unmarshaler interface。
#9
更多评论
我是先用字串格式接日期
然後再用第三方套件解析 string 的日期到 time.Time
github.com/araddon/dateparse
#1