【问题标题】:Custom Time Marshall Unmarshall自定义时间 Marshall Unmarshall
【发布时间】:2017-06-27 15:48:19
【问题描述】:

我有一个 MysqlTime 结构,它有自己的编组和解组。

type MysqlTime struct {
    time.Time
}

const MYSQL_TIME_FORMAT = "2006-01-02 15:04:05"

func (t *MysqlTime) UnmarshalJSON(b []byte) (err error) {
    s := strings.Trim(string(b), `\`)
    if s == "null" {
        t.Time = time.Time{}
        return
    }
    t.Time, err = time.Parse(MYSQL_TIME_FORMAT, s)
    return
}

func (t *MysqlTime) MarshalJSON() ([]byte, error) {
    if t.Time.UnixNano() == nilTime {
        return []byte("null"), nil
    }
    return []byte(fmt.Sprintf(`"%s"`, t.Time.Format(MYSQL_TIME_FORMAT))), nil
}

var nilTime = (time.Time{}).UnixNano()

func (t *MysqlTime) IsSet() bool {
    return t.UnixNano() != nilTime
}

现在我想用它...

type Foo struct {
    Time *MysqlTime
}

func main() {

    now := MysqlTime(time.Now())

    foo := Foo{}
    foo.Time = &now
}

错误:

cannot convert now (type time.Time) to type helpers.MysqlTime
cannot take the address of helpers.MysqlTime(now)

【问题讨论】:

    标签: json go time marshalling unmarshalling


    【解决方案1】:

    当这样做时:

    now := MysqlTime(time.Now())
    

    它会尝试将 Time 转换为您的 MysqlTime 类型(这会引发错误)。

    您的意思是像这样实际初始化内部Time 属性吗?

    now := MysqlTime{time.Now()}
    

    【讨论】:

      猜你喜欢
      • 2020-12-18
      • 2015-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多