json: cannot unmarshal object into a Go struct field
PROBLEM
1 min readJan 28, 2022
json: cannot unmarshal object into Go struct field
CODE
package mainimport (
"encoding/json"
"fmt"
)// DTO object
type mould struct {
Particle tiny
}type tiny interface {
GetName() string
}// Implement the interface
type speck struct {
Name string `json:"name"`
}func (s *speck) GetName() string {
return s.Name
}// Constructor
func NewSpeck(name string) tiny {
return &speck{
Name: name,
}
}//
func main() {
dirt := NewSpeck("space") brown := &mould{}
brown.Particle = dirt
brownBytes, err := json.Marshal(brown) if err != nil {
panic("marshal error")
} brownLike := &mould{} // unmarshal has no "idea" of how to unpack!
err = json.Unmarshal(brownBytes, &brownLike)
if err != nil {
panic("unmarshal err=%+v\n", err)
return
}
}
The error is:
go run unmarshal_interface.go
panic: json: cannot unmarshal object into Go struct field mould.Particle of type main.tiny
The problem with code is the inability of the Go runtime to get the target struct for unmarshaling.
Unmarshal essentially copies the byte array to a struct type. However, in the…