Golang解码包含特殊字符键的BSON到结构体的方法

huangapple go评论77阅读模式
英文:

Golang Decode a BSON with special character Keys to a struct

问题

我有一个名为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,那么它将无法被导出。

我该如何解决这个问题?

英文:

I have a Golang struct called Person where all the properties have to be exported:

type Person struct {
	Id         string
	Name       string 
}

Now I need to encode my MongoDB BSON response to this Person struct. The BSON looks like:

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

The Golang code to encode the BSON is:

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

The Problem:

  1. _id is not getting encoded into Id
  2. If I change the Person property into _Id, then it won't be exported.

How can I solve this problem?

答案1

得分: 1

使用json标签定义你的结构体-

type Person struct {
    Id   string `json:"_id"`
    Name string // 这个字段与json匹配,所以不需要映射
}
英文:

Define your struct with json tag-

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

答案2

得分: 1

我尝试添加一个类似于以下的json标签:

type Person struct {
    Id         string   `json:"_id"`
    Name       string  // 这个字段与json匹配,所以不需要映射
}

但是仍然不起作用。因为Mongodb返回的是类型为bson.ObjectId的'_id'。因此,将结构体标签更改为bson:"_id",并且Person结构体的类型已从string更改为bson.ObjectId。更改如下:

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

这样就可以了!

英文:

I tried to put a json tag like ,

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

But still it didn't work. Because the Mongodb returns '_id' which is of type bson.ObjectId . Hence changing the Struct tag to bson:"_id" and the type of the Person struct has been changed from string to bson.ObjectId. The changes done are as follows ,

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

And It works!

huangapple
  • 本文由 发表于 2017年7月9日 11:59:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/44992835.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定