Golang解码具有特殊字符的BSON到结构

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?

Define your struct with json tag-

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

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!