1 回答

TA貢獻(xiàn)1783條經(jīng)驗(yàn) 獲得超4個(gè)贊
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 關(guān)注
- 187 瀏覽
添加回答
舉報(bào)