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

Golang嵌套结构没有被省略

Golang嵌套结构没有被省略

Go
侃侃尔雅 2023-01-03 15:53:10
我想省略嵌套在 JSON 请求中的某些结构。我在 golang 上创建了一个 rest API,它从 http 请求中读取消息正文,将其解码为代码中定义的结构并将其插入 Mongo DB我的结构如下。请注意,对于嵌套结构C,我使用了一个指针以便能够省略它。type A struct {    Title        string        `json:"title"`    Text         string        `json:"text"`    Data         B             `json:"data"`}type B struct {    Product      *C            `json:"product,omitempty"`    ExternalLink string        `json:"external_link,omitempty"`}type C struct {    Name          string       `json:"name"`     Id            int          `json:"id"`   }这是我解码它的方式(没有去 Json.Unmarshall 因为我读到对于 http 主体,解码应该在unmarshall上使用)func NewMessage(req *http.Request) *A {      var newMessage *A      json.NewDecoder(req.Body).Decode(&newMessage)      messageInData := newMessage      return newMessage}返回时的“newMessage”直接插入到 Mongo 中。但是,即使请求有效负载不包含诸如结构 C 之类的对象,如下所示{    "title": "First message from GoLang",    "text": "Hello Dastgyr",    "data": {             "external_link": "some link here"             //no product object (C struct) here             }}插入到 Mongo 中的对象仍然包含具有空值的结构 C,如下所示{    "title": "First message from GoLang",    "text": "Hello Dastgyr",    "data": {             "product": null,             "external_link": "some link here"             }}我也尝试过在 Struct A 中使用 B 作为指针,但无济于事type A struct {    Title        string        `json:"title"`    Text         string        `json:"text"`    Data         *B            `json:"data,omitempty"`}我希望能够省略某些嵌套结构。尽管使用了指针,但我想要的结构仍然没有遗漏。我在定义结构时犯了什么错误?对 golang 还是新手,所以向正确的方向推动会有所帮助
查看完整描述

1 回答

?
手掌心

TA贡献1942条经验 获得超3个赞

您正在使用 json 标签进行 json 解封送处理,它似乎是正确的解封送处理(因为您没有提到任何错误而得出结论,并继续使用 MongoDB)


如何将数据添加到 MongoDB 是完全不同的事情,与您的 JSON 标记无关。它使用 bson 标签,如果您希望使用相同的结构作为 mongo DB 模型表示,则需要添加它们。是这样的:


type A struct {

    Title        string        `json:"title" bson:"title"`

    Text         string        `json:"text" bson:"text"`

    Data         *B            `json:"data,omitempty" bson:"data,omitempty"`

}

请记住,golang 中的标签只是一些添加了结构的元数据,一些代码实际读取并作用于该结构。json 库识别并处理json:""标签,而您可能使用的官方 go mongodb 库将处理bson:""标签。


查看完整回答
反对 回复 2023-01-03
  • 1 回答
  • 0 关注
  • 57 浏览
慕课专栏
更多

添加回答

举报

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