为了账号安全,请及时绑定邮箱和手机立即绑定

我可以在 mgo 中使用 json 标签作为 bson 标签吗?

我可以在 mgo 中使用 json 标签作为 bson 标签吗?

Go
子衿沉夜 2021-11-22 15:28:11
我thrift在我的项目中使用,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"`}如您所见,thrift 已经生成json tags(但是no bson tags),当我使用mgo保存记录时,mgo将自动转换:JdId -> jdidCvId -> cvidStatus -> statusAcceptTimeStamp -> 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吗?
查看完整描述

2 回答

?
慕田峪9158850

TA贡献1794条经验 获得超7个赞

MongoDB 实际上将数据存储为二进制 JSON(bson),这与 JSON 不同。这有点令人困惑,因为如果您使用 mongo shell 访问数据库,您将返回原始 JSON,但它实际上是一种转换,而不是存储格式。因此,在将数据存储到数据库时,“mgo”驱动程序序列化为bson。


此序列化忽略json导出键,并通过默认为结构字段的小写版本选择适当的名称。(请参阅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 上提供的链接中指定了这些类型的内容。希望有帮助!


查看完整回答
反对 回复 2021-11-22
?
开满天机

TA贡献1786条经验 获得超13个赞

您可以使用以下(来自 thrift 测试文件 git.apache.org/thrift.git/lib/go/test/GoTagTest.thrift)


struct tagged {

    1: string string_thing,

    2: i64 int_thing (go.tag = "json:\"int_thing,string\""),

    3: optional i64 optional_int_thing

}


查看完整回答
反对 回复 2021-11-22
  • 2 回答
  • 0 关注
  • 170 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信