- I have 2
struct
containing a field with the same label (id
) and the same JSON annotation (`json:"id"`). - One
struct
(Bar
) includes the fields labels and their values from the otherstruct
(Foo
).
I would like to JSON marshal the wrapper struct
Bar
with both the id
fields, but the inner one with a different JSON annotation (e.g. `json:"foo_id"`). I can not find a way to do it, but it looks like something that should be doable?
Having a quick look here https://golang.org/pkg/encoding/json/ I can not find the solution.
Is it possible at all? Is there any work around? I am trying to avoid all the boiler plate of get/set to copy/paste values between structs, I hope this is doable somehow.
package main
import (
"encoding/json"
"fmt"
)
type Foo struct {
ID int `json:"id"`
Stuff string `json:"stuff"`
}
type Bar struct {
ID int `json:"id"`
Foo
// the following does not work,
// I've tried a few variations with no luck so far
// Foo.ID int `json:"foo_id"`
OtherStuff string `json:"other_stuff"`
}
func main() {
foo := Foo{ID: 123, Stuff: "abc" }
bar := Bar{ID: 456, OtherStuff: "xyz", Foo: foo }
fooJsonStr, _ := json.Marshal(foo)
barJsonStr, _ := json.Marshal(bar)
fmt.Printf("Foo: %s
", fooJsonStr)
fmt.Printf("Bar: %s
", barJsonStr)
}
Gives this output:
Foo: {"id":123,"stuff":"abc"}
Bar: {"id":456,"stuff":"abc","other_stuff":"xyz"}