1

I am trying to read some JSON and unmarshal it into a data structure, defined below.

type TaskGroup struct {
    GroupName  string             `json:"groupName"`
    ModuleType modules.ModuleType `json:"module"`
    Project    string             `json:"project"`
    Tasks      map[string]*Task   `json:"tasks"`
}


type Task struct {
    Price       float64         `json:"price"`
    TaskOpts    modules.Module  `json:"opts"`
}

where Module is:

type Module interface {
    Run(ctx context.Context)
}

which are implemented by:

type ModuleA struct {
    TaskType  modules.ModuleType
    ProductID string
}
type ModuleB struct {
    TaskType modules.ModuleType
    CMID     string
}

So when I try to unmarshal JSON from a file, I get the following error:

json: cannot unmarshal object into Go struct field Task.tasks.opts of type modules.Module

Is this possible? Not sure if this is an error elsewhere or it's because I'm trying to unmarshal into an interface

JC1
  • 849
  • 13
  • 25
  • I second that. I have exactly the same question, but all solutions that I was able to find seem to be irrelevant. Even if I have method that can convert `[]byte` to implementation of `Module` it can not be used, because It's impossible to implement `UnmarshalJSON` for the `Module` as it's an interface. Implementing `UnmarshalJSON` for the whole `TaskGroup` makes no sense, because it will require to parse all fields. – Dmitry K Oct 25 '22 at 15:19

0 Answers0