1 回答
TA贡献1783条经验 获得超4个赞
type UserItem struct {
User string `json:"user"`
Status string `json:"status"`
}
type UserList []UserItem
func (ul *UserList) UnmarshalJSON(data []byte) error {
switch {
case len(data) == 0 || string(data) == `null`:
return nil
case data[0] == '[': // assume it's a JSON array
return json.Unmarshal(data, (*[]UserItem)(ul))
case data[0] == '{': // assume it's a JSON object
obj := make(map[string]UserItem)
if err := json.Unmarshal(data, &obj); err != nil {
return err
}
for _, v := range obj {
*ul = append(*ul, v)
}
return nil
default:
return fmt.Errorf("unsupported json type")
}
return nil
}
https://go.dev/play/p/Y5PAjrmPhy2
- 1 回答
- 0 关注
- 160 浏览
添加回答
举报