【发布时间】:2017-11-30 07:26:15
【问题描述】:
当我从我的数据库中抓取一个帖子并尝试将其呈现为 JSON 时,我遇到了一些问题:
type PostBSON struct {
Id bson.ObjectId `bson:"_id,omitempty"`
Title string `bson:"title"`
}
// ...
postBSON := PostBSON{}
id := bson.ObjectIdHex(postJSON.Id)
err = c.Find(bson.M{"_id": id}).One(&postBSON)
// ...
response, err := bson.MarshalJSON(postBSON)
MarshalJSON 不为我处理十六进制 Id (ObjectId)。因此我得到:
{"Id":{"$oid":"5a1f65646d4864a967028cce"}, "Title": "blah"}
清理输出的正确方法是什么?
{"Id":"5a1f65646d4864a967028cce", "Title": "blah"}
编辑:我编写了自己的 stringify as described here。 这是一个高性能的解决方案吗? 它是白痴吗?
func (p PostBSON) String() string {
return fmt.Sprintf(`
{
"_id": "%s",
"title": "%s",
"content": "%s",
"created": "%s"
}`,
p.Id.Hex(),
p.Title,
p.Content,
p.Id.Time(),
)
【问题讨论】: