【问题标题】:Golang Decode a BSON with special character Keys to a structGolang 将带有特殊字符键的 BSON 解码为结构
【发布时间】:2017-07-09 17:13:46
【问题描述】:

我有一个名为 Person 的 Golang 结构,其中所有属性都必须导出:

type Person struct {
    Id         string
    Name       string 
}

现在我需要将我的 MongoDB BSON 响应编码到这个 Person 结构。 BSON 看起来像:

{
  "_id": "ajshJSH78N",
  "Name": "Athavan Kanapuli"
}

编码 BSON 的 Golang 代码是:

    mongoRecord := Person{}
    c := response.session.DB("mydb").C("users")
    err := c.Find(bson.M{"username": Credentials.Username, "password": Credentials.Password}).One(&mongoRecord)

问题:

  1. _id 没有被编码成 Id
  2. 如果我将Person 属性更改为_Id,则不会导出。

我该如何解决这个问题?

【问题讨论】:

  • 根据您的回答,这个问题是错误的:您根本不是在解码 JSON,而是在解码 BSON。

标签: go bson


【解决方案1】:

json 标签定义你的结构-

type Person struct {
    Id         string   `json:"_id"`
    Name       string  // this field match with json, so mapping not need
}

【讨论】:

    【解决方案2】:

    我尝试放置一个 json 标记,例如,

    type Person struct {
        Id         string   `json:"_id"`
        Name       string  // this field match with json, so mapping not need
    }
    

    但是还是不行。因为 Mongodb 返回类型为 bson.ObjectId 的 '_id' 。因此,将 Struct 标记更改为 bson:"_id",并且 Person 结构的类型已从字符串更改为 bson.ObjectId。所做的更改如下,

    type Person struct {
        Id         bson.ObjectId `bson:"_id"`
        Name       string
        UserName   string
        IsAdmin    bool
        IsApprover bool
    }
    

    而且它有效!

    【讨论】:

    • 如果bson 标签有效,那是因为您根本没有解码 JSON。
    猜你喜欢
    • 2021-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-21
    • 2020-02-07
    • 2021-08-29
    • 1970-01-01
    相关资源
    最近更新 更多