2

我有一个带有 updated_at 字段的结构,我想将其 JSON 编码为 un​​ix 时间戳。

我尝试了以下似乎不起作用的方法,updated_at 字段永远不会从 MongoDB 文档中解组:

type Timestamp time.now

func (t Timestamp) MarshalJSON() ([]byte, error) {
    ts := time.Time(t).Unix()
    fmt.Println(ts)
    stamp := fmt.Sprint(ts)

    return []byte(stamp), nil
}


type User struct {
    UpdatedAt *Timestamp `bson:"updated_at,omitempty" json:"updated_at,omitempty"`
}

我找到了一个临时解决方案,编写结构的 MarshalJSON 函数,执行如下操作(将 UpdatedAt 类型更改为 *time.Time):

func (u *User) MarshalJSON() ([]byte, error) {
    out := make(map[string]interface{})

    if u.UpdatedAt != nil && !u.UpdatedAt.IsZero() {
        out["updated_at"] = u.UpdatedAt.Unix()
    }

    return json.Marshal(out)
}

这样做有更好或更优雅的解决方案吗?

4

2 回答 2

0

在其他地方找到了解决方案并写了一篇关于它的帖子 - https://medium.com/coding-and-deploying-in-the-cloud/time-stamps-in-golang-abcaf581b72f

为了处理 mgo 的编组/解组,必须实现 GetBSON() 和 SetBSON() 函数。

于 2014-09-05T20:57:22.293 回答
-1

您的代码不起作用,因为您需要MarshalJSON*Timestampnot上实现Timestamp

func (t *Timestamp) MarshalJSON() ([]byte, error) { .... }
于 2014-09-04T21:58:42.673 回答