英文:
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)
问题:
_id
没有被编码为Id
。- 如果我将
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:
_id
is not getting encoded intoId
- 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!
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论