One way to do this is to forgo the custom UnmarshalJSON
function entirely and just use the basic JSON notation, i.e.:
type Outer struct {
Inner
Num int `json:"num"`
}
type Inner struct {
Data string `json:"data"`
}
You lose some of the more granular capabilities you could have with a custom unmarshalling method, but when you're unmarshalling a struct with mostly primitive fields like strings, you really don't need to worry about that.
Example in go playground
If you really need custom unmarshalling, you could use composition, and give the struct a custom json encoding tag and have the struct contain the fields you want to play with. So if data
is something that will contain multiple complex fields, you could just change Inner
to reflect those fields, like this:
type Outer struct {
Data Inner `json:"data"`
Num int `json:"num"`
}
type Inner struct {
Thing string `json:"thing"`
OtherThing int `json:"otherThing"`
}
Example in go playground
Once again, this doesn't have a custom unmarshalling function, but that can be scraped together for Inner
easily enough. (Personally, I'd forgo the use of custom unmarshal functions entirely in any given case and just use encoding tags unless I absolutely had to use the unmarshalling function.)