我有以下最小复制,当此代码运行时它会在basicMap[key] = valuebecause处抛出异常assignment to entry in nil map,但是它仅在类型为[]CustomMap- 当我将 a 用于CustomMap单个项目时才执行此操作,它工作得很好。
有没有办法在 go 中解组自定义对象数组?
package main
import "encoding/json"
type CustomMap map[string]any
type Payload struct {
Items []CustomMap `json:"items"`
}
func mapToBasicMap(basicMap CustomMap, aMap map[string]any) {
for key, value := range aMap {
basicMap[key] = value
}
}
func (this CustomMap) UnmarshalJSON(data []byte) error {
var aMap map[string]any = make(map[string]any)
json.Unmarshal(data, &aMap)
mapToBasicMap(this, aMap)
return nil
}
func main() {
payload := Payload{}
json.Unmarshal([]byte("{\"items\":[{\"item1\": 1}]}"), &payload)
}
ABOUTYOU
相关分类