【问题标题】:How to correctly bson.MarshalJSON(myStruct) with an ObjectID?如何正确使用 ObjectID 的 bson.MarshalJSON(myStruct)?
【发布时间】: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(),
  )

【问题讨论】:

    标签: mongodb go mgo


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-06
      • 2019-09-16
      • 2017-07-06
      • 1970-01-01
      • 1970-01-01
      • 2014-03-09
      • 2019-02-14
      • 1970-01-01
      相关资源
      最近更新 更多