将结构切片作为数字切片进行编组

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 接口来实现任何自定义编组逻辑。

所以只需在 Role 上实现 MarshalJSON() ([]byte, error) 方法,在其中将其编组为一个简单的 int 数字。

它可能是这样的:

func (r Role) MarshalJSON() ([]byte, error) {
    return json.Marshal(r.Role)
}

如您所见,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)
}

输出如您所愿(在 Go Playground 上尝试):

{"id":"abc","roles":[1,2,3]}