dqq3623 2017-11-30 07:26
浏览 174
已采纳

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

When I take my grab a post form my db and try and render it to JSON I run into some problems:

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)

The MarshalJSON doesn't handle hexing Id (ObjectId) for me . Thus I get:

{"Id":{"$oid":"5a1f65646d4864a967028cce"}, "Title": "blah"}

What is the correct way to clean up the output?

{"Id":"5a1f65646d4864a967028cce", "Title": "blah"}

Edit: I wrote my own stringify as described here. Is this a performant solution? And is it idiotmatic go?

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(),
  )
  • 写回答

1条回答 默认 最新

  • dqxsuig64994 2017-11-30 09:41
    关注

    You can implement a MarshalJSON to satisfy json.Marshaler interface, e.g.:

    func (a PostBSON) MarshalJSON() ([]byte, error) {
        m := map[string]interface{}{
            "id": a.Id.Hex(),
            "title": a.Title,
        }
        return json.Marshal(m)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?