如何使用 ObjectID 正确 bson.MarshalJSON(myStruct)?

How to correctly bson.MarshalJSON(myStruct) with an ObjectID?

当我从我的数据库中获取 post 并尝试将其渲染到 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(),
  )

您可以实现一个 MarshalJSON 来满足 json.Marshaler 接口,例如:

func (a PostBSON) MarshalJSON() ([]byte, error) {
    m := map[string]interface{}{
        "id": a.Id.Hex(),
        "title": a.Title,
    }
    return json.Marshal(m)
}