[英]Marshal slice of structs as slice of numbers
我試圖弄清楚編組到JSON字符串的最佳方法是什么:
type User struct {
Id string `json:"id"`
Roles []Role `json:"roles"`
}
type Role struct {
Id string `json:"-"`
Role int
}
獲取JSON輸出,例如: {"id": "abc", "roles": [1, 2, 3]}
您可以通過實現json.Marshaler
接口來實現任何自定義的封送處理邏輯。
所以,簡單地實現MarshalJSON() ([]byte, error)
的方法Role
,在其中元帥它像一個簡單的int
數。
它看起來像這樣:
func (r Role) MarshalJSON() ([]byte, error) {
return json.Marshal(r.Role)
}
如您所見, Role.MarshalJSON()
僅Role.Role
int
字段,而不Role.Role
整個struct
。
測試它:
u := User{
Id: "abc",
Roles: []Role{
Role{Id: "a", Role: 1},
Role{Id: "b", Role: 2},
Role{Id: "c", Role: 3},
},
}
if err := json.NewEncoder(os.Stdout).Encode(u); err != nil {
panic(err)
}
輸出是您期望的(在Go Playground上嘗試):
{"id":"abc","roles":[1,2,3]}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.