rza*_*jac 3 json struct marshalling go slice
我试图找出将 JSON 字符串编组到以下结构的最佳方法:
type User struct {
Id string `json:"id"`
Roles []Role `json:"roles"`
}
type Role struct {
Id string `json:"-"`
Role int
}
Run Code Online (Sandbox Code Playgroud)
获取 JSON 输出,例如:{"id": "abc", "roles": [1, 2, 3]}
您可以通过实现该json.Marshaler接口来实现任何自定义封送逻辑。
因此,只需实现MarshalJSON() ([]byte, error)on 的方法Role,在其中将其像简单的int数字一样进行封送。
它可能是这样的:
func (r Role) MarshalJSON() ([]byte, error) {
return json.Marshal(r.Role)
}
Run Code Online (Sandbox Code Playgroud)
如您所见,Role.MarshalJSON()仅编组该Role.Role int字段,而不是整个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)
}
Run Code Online (Sandbox Code Playgroud)
{"id":"abc","roles":[1,2,3]}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1009 次 |
| 最近记录: |