Go 未加载JSON输出中的关联字段时,如何忽略该字段?

Go 未加载JSON输出中的关联字段时,如何忽略该字段?,go,model,go-gorm,go-gin,Go,Model,Go Gorm,Go Gin,在我的gorm模型中,我有用户和配置文件: type User struct { ID int Username string Password string `json:"-"` Profile Profile } type Profile struct { UserID int Gender string Places

在我的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和Username两个字段时,即使我没有预加载()或相关()配置文件,仍然有一个空的字段集:

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"`
}

若要省略它们,应该使用结构的指针。如果未加载,它将变为nil,并且不会出现在JSON中

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

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