场景

数据库为mongodb,驱动为mgo。从库中取数据后以json格式返给调用者。

  1. type MyStruct struct{
  2. Time time.Time
  3. }

Time的MarshalJSON实现是转化为RFC3339格式的时间,
若没有赋值,格式化后为0001-01-01T00:00:00Z, 对调用者极不友好

null
json:",omitempty"
0值
time.Time*time.Time
0001-01-01T00:00:00Z

姿势不优雅

json.Marshaler
null
  1. type CustomTime struct{
  2. time.Time
  3. }
  4. func (t CustomTime) MarshalJSON() ([]byte, error) {
  5. fmt.Println(t.String())
  6. if t.Time.IsZero() {
  7. return []byte("null"), nil
  8. }
  9. return t.Time.MarshalJSON()
  10. }

大功告成

其实并没有。经测试发现,没赋值的变成了null,有正常值的也变成了null

time.Time

解决:

bson.Getterbson.Setter
  1. func (t CustomTime) GetBSON() (interface{}, error) {
  2. if t.Time.IsZero() {
  3. return nil, nil
  4. }
  5. return t.Time, nil
  6. }
  7. func (t *CustomTime) SetBSON(raw bson.Raw) error {
  8. var tm time.Time
  9. if err := raw.Unmarshal(&tm); err != nil {
  10. return err
  11. }
  12. t.Time = tm
  13. return nil
  14. }