某些接口不需要关联数据,在查询数据时如何取消,即不显示空的关联结构体?
|
janxinJul 11, 2019
1
看看文档? 印象中有的
|
|
pubbyJul 11, 2019
3
是指接口返回数据中隐藏一些信息吗 ?
func handlerApiXXX(w httpResponseWriter,r *http.Request) { var user model.User //.. get User type T struct{ model.User // 隐藏 password_hash, salt 信息 OmitPassword bool `json:"password_hash,omitempty"` OmitSalt bool `json:"salt,omitempty"` } var t = T{User: user} _ = json.NewEcode(w).Encode(t) } |
|
4
@pubby 是这样的
type user struct { ID int32 Name string //关联账户 Account Account `gorm:"foreignkey:UserId"` } 正常查询结果是有 Account 关联数据的,但是另一个接口 不需要 Account 的数据 ,我如何在不改变结构体关联关系而取消关联,(即不在查询结果中只显示 ID,Name;不显示 Account 数据结构) |
|
5
@pubby
是这样的 type user struct { ID int32 Name string //关联账户 Account Account `gorm:"foreignkey:UserId"` } type Account struct { ID int32 UserId int32 ...... } 正常查询结果是有 Account 关联数据的,但是另一个接口 不需要 Account 的数据 ,我如何在不改变结构体关联关系而取消关联,(即在查询结果中只显示 ID,Name;不显示 Account 数据结构) |
|
AoangJul 11, 2019 via Android
6
type T struct {
Username string `json:"username"` Password string `json:"-"` } |
|
pubbyJul 11, 2019
7
type User struct {
ID int32 Name string //关联账户 Account Account `gorm:"foreignkey:UserId" json:"-"` // json 结果将不包含 Account 信息 } 如果 User 是其他包的无法修改 就在输出时临时定义一个 struct,利用 omitempty 特性把空值移除 type T struct { User OmitAccount bool `json:"Account,omitempty"` // 只要这里是空值 false, json 输出将不会包含 Account } |
|
sunmoon1983Jul 11, 2019
8
插眼
|
|
esliznJul 11, 2019
9
|
|
10
@pubby omitempty 可行,但是对于列表查询如何处理里面的 “ account ” 如:
var list []User 数据结构如下: { "data":[ { "id": 1, "name":"name", "account":{ "id":0, "mobile":"", "password":"" } },{ "id": 2, "name":"names", "account":{ "id":0, "mobile":"", "password":"" } }, ] } |