I'm trying to build a complicated, deeply-nested JSON payload. The total number of structs in it numbers in the hundreds, but they can all be sorted into three or four different classifications, each of which need to be marshaled a little bit differently. Specifically, I need to add an arbitrary field to their json encodings, but each classification requires a different field.
The problem is I can't reuse the MarshalJSON() method for anything that isn't a Book:
func (b Book) MarshalJSON() ([]byte, error) {
return json.Marshal(struct {
FakeBook
Genre string
}{
FakeBook: FakeBook(b),
Genre: "Satire",
})
}
I tried pulling the logic in MarshalJSON out to its own function, then letting MarshalJSON() call that function, but it ends up being infinitely recursive (
http://play.golang.org/p/ImRmt5V3hd), which makes sense once you poke at the source code of encoding/json/encode.go.
Is there any other way to share the same MarshalJSON() implementation between structs, or perhaps another way to hook into "encoding/json" for this purpose?