登录
首页 >  Golang >  Go问答

如何在 JSON 输出中排除未加载的关联字段?

来源:stackoverflow

时间:2024-03-02 22:57:26 143浏览 收藏

编程并不是一个机械性的工作,而是需要有思考,有创新的工作,语法是固定的,但解决问题的思路则是依靠人的思维,这就需要我们坚持学习和更新自己的知识。今天golang学习网就整理分享《如何在 JSON 输出中排除未加载的关联字段?》,文章讲解的知识点主要包括,如果你对Golang方面的知识点感兴趣,就不要错过golang学习网,在这可以对大家的知识积累有所帮助,助力开发能力的提升。

问题内容

在我的 gorm 模型中,我有用户和个人资料:

type user struct {
    id            int    
    username      string
    password      string     `json:"-"`

    profile profile
}

type profile struct {
    userid        int    
    gender        string
    places        string

    //...and many more fields
}

当我使用以下方式寻找个人资料的完整显示时:

db.preload("profile").where("id = ?", 1).first(&user)
c.json(200, user)

客户端收到的 json 结果非常好:

{
    "id": 1,
    "username": {
        "string": "",
        "valid": false
    },
    "profile": {
        "userid": 1,
        "gender": "men",
        "places": "home and staying home",
        // ...and many more
    },
}

但是当我只想列出id和用户名两个字段时,即使我没有preload()或related() profile,仍然有一个空集:

db.Where("id = ?", 1).First(&user)
c.JSON(200, user) 

// Result
{
    "ID": 1,
    "Username": {
        "String": "",
        "Valid": false
    },
    //below is redundant in this situation
    "Profile": {
        "UserID": 0,
        "Gender": "",
        "Places": "",
        // ...And many more 0 or "" fields
    },
}

我的问题是每次未加载时如何忽略 json 响应中的配置文件字段?为了节省一些转账费用


解决方案


如果你想省略它们,你应该使用结构体的指针。如果不加载就会变成nil,并且不会出现在json中

type User struct {
    ID            int    
    Username      string
    Password      string     `json:"-"`

    Profile *Profile `json:",omitempty"`
}

终于介绍完啦!小伙伴们,这篇关于《如何在 JSON 输出中排除未加载的关联字段?》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!

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