1 回答
TA贡献1848条经验 获得超2个赞
您可以将自定义解组器与地图一起使用:
type ResultList []Result
func (ls *ResultList) UnmarshalJSON(data []byte) error {
var obj map[string]json.RawMessage
if err := json.Unmarshal(data, &obj); err != nil {
return err
}
for key, raw := range obj {
r := Result{Key: key}
if raw[0] == '[' { // assume array of ints
if err := json.Unmarshal(raw, &r.Value); err != nil {
return err
}
} else { // assume single int
var i int
if err := json.Unmarshal(raw, &i); err != nil {
return err
}
r.Value = append(r.Value, i)
}
*ls = append(*ls, r)
}
return nil
}
https://go.dev/play/p/Epd6cLwyWUm
或者,如果您需要保留订单,您可以标记输入:
type ResultList []Result
func (ls *ResultList) UnmarshalJSON(data []byte) error {
d := json.NewDecoder(bytes.NewReader(data))
i := -1
for {
t, err := d.Token()
if err == io.EOF {
break
}
if err != nil {
return err
}
switch v := t.(type) {
case string:
*ls = append(*ls, Result{Key: v})
i += 1
case float64:
(*ls)[i].Value = append((*ls)[i].Value, int(v))
}
}
return nil
}
https://go.dev/play/p/nABjw5IHZ7R
- 1 回答
- 0 关注
- 70 浏览
添加回答
举报