如何在go中从json中删除字段?

如何在go中从json中删除字段?,go,Go,我的代码中有这个结构 type AppVersion struct { Id int64 `json:"id"` App App `json:"app,omitempty" out:"false"` AppId int64 `sql:"not null" json:"app_id"` Version string `sql:"not null" json:"ve

我的代码中有这个结构

type AppVersion struct {
    Id            int64     `json:"id"`
    App           App       `json:"app,omitempty" out:"false"`
    AppId         int64     `sql:"not null" json:"app_id"`
    Version       string    `sql:"not null" json:"version"`
    Sessions      []Session `json:"-"`
    SessionsCount int       `sql:"-"`
    CreatedAt     time.Time `json:"created_at"`
    UpdatedAt     time.Time `json:"updated_at"`
    DeletedAt     time.Time `json:"deleted_at"`
}
我正在构建一个Web服务,不需要发送JSON中的
App
字段。 我尝试了一些方法从JSON中删除该字段,但没有成功

我怎样才能做到这一点? 有没有办法将struct设置为空


我使用GORM作为数据库访问层,因此我不确定是否可以执行
App*App
,您知道它是否可以工作吗?

您应该能够将数据结构包装到自定义类型中,该类型隐藏App字段:

type ExportAppVersion struct {
   AppVersion
   App `json:"-"`
}
这将隐藏
App
字段,使其不会暴露

type AppVersion struct {
    Id            int64     `json:"id"`
    App           App       `json:"-"`
    AppId         int64     `sql:"not null" json:"app_id"`
    Version       string    `sql:"not null" json:"version"`
    Sessions      []Session `json:"-"`
    SessionsCount int       `sql:"-"`
    CreatedAt     time.Time `json:"created_at"`
    UpdatedAt     time.Time `json:"updated_at"`
    DeletedAt     time.Time `json:"deleted_at"`
}

更多信息-

您尝试过吗?我怀疑它会起作用。我已经试过了,但它不起作用,数据库创建/迁移有问题。嗯,这听起来像是GORM的问题。如果您想在
json
包的规范之外进一步控制序列化,您可以在
AppVersion
上实现自己的
json.Marshaler
json.Unmarshaler
,如何创建自定义封送拆收器?您可以在
AppVersion
上实现
MarshalJSON
UnmarshalJSON
。如果这些方法存在,
json
包将调用它们,而不是使用它自己的基于反射的封送处理因此,在解码json时,我会错过该字段。此外,我希望可以选择控制何时返回或不返回。如果要反序列化/发送,请不要将其包装在此结构中。