3 回答

TA貢獻1834條經驗 獲得超8個贊
為什么你只是這樣做下面
type SubPaper struct {
PID int `json:"pID"`
PPwd string `json:"pPwd"`
}
type Paper struct {
SubPaper
PTitle string `json:"pTitle"`
PDesc string `json:"pDesc"`
}
如果你想要完整的回應,然后整理報紙
和 SubPaper 選擇性的東西

TA貢獻1871條經驗 獲得超13個贊
在標簽中使用 omitempty。創建結構體實例時無需指定要包含的項目。
type Paper struct {
PID int `json:"pID,omitempty"`
PTitle string `json:"pTitle"`
PDesc string `json:"pDesc"`
PPwd string `json:"pPwd,omitempty"`
}
func main() {
u := Paper{PTitle: "Title 1", PDesc: "Desc 1"}
b, _ := json.Marshal(u)
fmt.Println(string(b))
}
打?。簕“pTitle”:“標題 1”,“pDesc”:“描述 1”}
唯一的問題是,如果 PID 明確為 0,那么它仍然會忽略它。
喜歡:
Paper{PTitle: "Title 1", PDesc: "Desc 1", PID:0} 那么它仍然會打印 {"pTitle":"Title 1","pDesc":"Desc 1"}
另一種使用嵌入類型的方法:
請注意,嵌入類型必須是指針,以便它可以為 nil,然后 omitempty 可以排除它。
type Paper struct {
PID int `json:"pID"`
PPwd string `json:"pPwd"`
}
type BriefPaper struct {
PTitle string `json:"pTitle"`
PDesc string `json:"pDesc"`
*Paper `json:",omitempty"`
}
func main() {
u := BriefPaper{PTitle: "Title 1", PDesc: "Desc 1"}
b, _ := json.Marshal(u)
fmt.Println(string(b))
}
打?。簕“pTitle”:“標題 1”,“pDesc”:“描述 1”}
如果需要紙張的嵌套內部結構,請將其標記為 *Paperjson:"paper,omitempty"

TA貢獻1804條經驗 獲得超3個贊
也許最簡單的方法是創建一個 struct embeds Paper,并隱藏要隱藏的字段:
type Paper struct {
PID int `json:"pID"`
PTitle string `json:"pTitle"`
PDesc string `json:"pDesc"`
PPwd string `json:"pPwd"`
}
type BriefPaper struct {
Paper
PID int `json:"pID,omitempty"` // Just make sure you
PPwd string `json:"pPwd,omitempty"` // don't set these fields!
}
p := Paper{ /* ... */ }
pBrief := BriefPaper{Paper: p}
現在,當編組時BriefPaper,字段PID和PPwd將被省略。
- 3 回答
- 0 關注
- 177 瀏覽
添加回答
舉報