如何使用mgo从文档中解组具名类型别名?

huangapple go评论92阅读模式
英文:

How to unmarshal a named type alias from a document with mgo?

问题

我有一个带有updated_at字段的结构体,我希望将其JSON编码为Unix时间戳。

我尝试了以下代码,但似乎不起作用,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)
}

是否有更好或更优雅的解决方案来实现这个需求?

英文:

I have a struct with updated_at field which I want to be JSON encoded as a unix timestamp.

I tried the following which doesn’t seem to work,
the updated_at field is never unmarshalled from the MongoDB document:

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"`
}

I found a temp solution, to write the struct’s MarshalJSON function, doing something like this (changing the UpdatedAt type to *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)
}

is there a better or more elegant solution for doing this?

答案1

得分: 0

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

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

英文:

found the solution elsewhere and wrote a post about it - https://medium.com/coding-and-deploying-in-the-cloud/time-stamps-in-golang-abcaf581b72f

for handling mgo's marshaling/unmarshaling one has to implement the GetBSON() and SetBSON() functions.

答案2

得分: -1

你的代码无法正常工作,因为你需要在*Timestamp而不是Timestamp上实现MarshalJSON方法。

func (t *Timestamp) MarshalJSON() ([]byte, error) { .... }
英文:

Your code isn't working because you need to implement MarshalJSON on *Timestamp not Timestamp.

func (t *Timestamp) MarshalJSON() ([]byte, error) { .... }

huangapple
  • 本文由 发表于 2014年9月4日 17:14:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/25661565.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定