【发布时间】:2012-11-16 18:38:07
【问题描述】:
我在根据类型 time.Time 创建自己的类型 Date 时遇到一些问题
我尝试按如下方式创建日期类型:
type Date time.Time
func (d Date) UnmarshalJSON(buf []byte) error {
var s string
json.Unmarshal(buf, &s)
t, err := time.Parse(timeLayout,s)
d= Date(t)
return err
}
func (d Date) MarshalJSON() ([]byte, error) {
b,_ := json.Marshal(d.Format(timeLayout))
return b,nil
}
这本身有效,我可以将此日期作为 time.Time 存储在 AppEngine 数据存储区中。 编组本身也有效, 但不起作用的是:然后当从 json 解组时,Date d 会填充该值。 据我了解,这是因为 unmarshalJson 函数创建了 Date 的副本。
所以当我更改 unmarshalJson 函数以使用指向日期的指针时 那我就不能用了:
d=Date(t)
所以第一个问题,有解决办法吗?
我现在所做的是重写代码如下:
type Date struct {
t time.Time
}
func (d *Date) UnmarshalJSON(buf []byte) error {
var s string
json.Unmarshal(buf, &s)
t, err := time.Parse(timeLayout,s)
d.t = t
return err
}
func (d Date) MarshalJSON() ([]byte, error) {
b,_ := json.Marshal(d.t.Format(timeLayout))
return b,nil
}
这可行,但在这种情况下 Date 不是 time.Time 的扩展类型,它只是 time.Time 类型的包装器。
有更好的解决方案吗?我还是新手。
我需要这个 Date 类型,有一个 Date only json 格式的类型,因为 Chrome 只支持 html5 类型:date 而不是 datetime。 并且方法覆盖在 go 中是不可能的(意味着覆盖 time.Time 类型的 un/marshalJson 方法)?
谢谢
【问题讨论】:
标签: go