亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何有選擇地為結構封送 JSON?

如何有選擇地為結構封送 JSON?

Go
叮當貓咪 2023-07-04 10:04:22
我有一個結構:type Paper struct {    PID    int    `json:"pID"`    PTitle string `json:"pTitle"`    PDesc  string `json:"pDesc"`    PPwd   string `json:"pPwd"`}大多數情況下,我會將整個結構編碼為 JSON。然而,有時,我需要該結構的簡短版本;即對一些屬性進行編碼,我應該如何實現這個功能?type BriefPaper struct {    PID    int    `json:"-"`      // not needed    PTitle string `json:"pTitle"`    PDesc  string `json:"pDesc"`    PPwd   string `json:"-"`      // not needed}我正在考慮創建一個子集結構,例如BriefPaper = SUBSET(Paper),但不確定如何在 Golang 中實現它。我希望我能做這樣的事情:p := Paper{ /* ... */ }pBrief := BriefPaper{}pBrief = p;p.MarshalJSON(); // if need full JSON, then marshal PaperpBrief.MarshalJSON(); // else, only encode some of the required properties是否可以?去
查看完整描述

3 回答

?
MMMHUHU

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 選擇性的東西


查看完整回答
反對 回復 2023-07-04
?
慕桂英4014372

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"


查看完整回答
反對 回復 2023-07-04
?
狐的傳說

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將被省略。


查看完整回答
反對 回復 2023-07-04
  • 3 回答
  • 0 關注
  • 177 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號