我在我的项目中使用thrift
,节俭将生成如下代码:
type CvJdRelationInfo struct {
JdId string `thrift:"jdId,1" json:"jdId"`
CvId string `thrift:"cvId,2" json:"cvId"`
Status int16 `thrift:"status,3" json:"status"`
AcceptTimestamp int64 `thrift:"acceptTimestamp,4" json:"acceptTimestamp"`
}
如您所见,节俭已经生成了json tags
(但是no bson tags
),当我使用mgo
保存记录时,mgo
将自动转换:
JdId -> jdid
CvId -> cvid
Status -> status
AcceptTimeStamp -> accepttimestamp
我需要的是:
type CvJdRelationInfo struct {
JdId string `thrift:"jdId,1" json:"jdId" bson:"jdId"`
CvId string `thrift:"cvId,2" json:"cvId" bson:"cvId"`
Status int16 `thrift:"status,3" json:"status" bson:"status"`
AcceptTimestamp int64 `thrift:"acceptTimestamp,4" json:"acceptTimestamp" bson:"acceptTimestamp"`
}
如您所见,bson tags
与json tags
相同。我可以将json tags
用作bson tags
吗?
MongoDB实际上将数据存储为二进制JSON(bson),这与JSON不同。这有点令人困惑,因为如果您使用mongo shell访问数据库,则会获取原始的JSON,但实际上是一种转换,而不是存储格式。因此,在将数据存储到数据库中时,“ mgo”驱动程序序列化为bson。
此序列化将忽略json
导出键,并通过默认使用struct字段的小写版本来选择适当的名称。 (请参阅bson.Marshal go doc。)如果指定bson
导出键,则它将忽略结构字段名称,并使用您指定为bson
导出键的名称。
例如,
type User struct {
Name string
UserAge int `bson:"age"`
Phone string `json:"phoneNumber"`
}
将在MongoDB中产生以下结构:
{
"name": "",
"age": 0,
"phone": ""
}
所以看来您的结构字段应该为您处理大多数事情。
直到被咬后您可能看不到的一个'陷阱',如果您未指定bson
导出键,则无法执行bson:",omitempty"
来保留空白字段,或者bson:",inline"
用于封送嵌入式(或嵌套)结构。
例如,这是处理嵌入式结构的方式:
type Employee struct { User `bson:",inline"` JobTitle string EmployeeId string Salary int }
这些东西在我在bson.Marshal上提供的链接中指定。希望能有所帮助!
您可以使用以下内容(来自旧版测试文件git.apache.org/thrift.git/lib/go/test/GoTagTest.thrift)