英文:
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) { .... }
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论