登录
首页 >  Golang >  Go问答

Golang 不允许省略嵌套结构

来源:stackoverflow

时间:2024-02-06 20:57:25 443浏览 收藏

有志者,事竟成!如果你在学习Golang,那么本文《Golang 不允许省略嵌套结构》,就很适合你!文章讲解的知识点主要包括,若是你对本文感兴趣,或者是想搞懂其中某个知识点,就请你继续往下看吧~

问题内容

我想省略 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 中。但是,即使请求有效负载不包含像 struct c 这样的对象,如下所示

{
    "title": "first message from golang",
    "text": "hello dastgyr",
    "data": {
             "external_link": "some link here"
             //no product object (c struct) here
             }
}

插入到 mongo 中的对象仍然包含 struct c,因为它具有 null 值,如下所示

{
    "title": "first message from golang",
    "text": "hello dastgyr",
    "data": {
             "product": null,
             "external_link": "some link here"
             }
}

我也尝试过使用 b 作为结构 a 中的指针,但无济于事

type A struct {
    Title        string        `json:"title"`
    Text         string        `json:"text"`
    Data         *B            `json:"data,omitempty"`
}

我希望能够省略某些嵌套结构。尽管使用了指针,但我想要的结构体仍然没有省略。我在定义结构时犯了什么错误?

对 golang 来说还是个新手,所以朝正确的方向推动会有所帮助


正确答案


您正在使用 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:"" 标签。

好了,本文到此结束,带大家了解了《Golang 不允许省略嵌套结构》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>