I have the following minimal reproduction, when this code runs it throws an exception at basicMap[key] = value
because assignment to entry in nil map
, however it only does this when the type is []CustomMap
- when I use a CustomMap
for a single item, it works just fine.
Is there a way of unmarshalling arrays of custom objects in 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)
}
CodePudding user response:
Unmarshal should have a pointer receiver. Make the target map before using assigning to its values.
func (this *CustomMap) UnmarshalJSON(data []byte) error {
var aMap map[string]any = make(map[string]any)
json.Unmarshal(data, &aMap)
*this = make(CustomMap)
mapToBasicMap(*this, aMap)
return nil
}
A different fix is to delete method CustomMap.UnmarshalJSON