由于
MarshalJSON匿名字段的方法
*meta将提升为
MyStruct,因此在
encoding/json将MyStruct编组后,程序包将使用该方法。
您可以做的是,您可以像这样在MyStruct上
meta实现
Marshaller接口,而不是让其实现接口:
package mainimport ( "fmt" "encoding/json" "strconv")type MyStruct struct { *meta Contents []interface{}}type meta struct { Id int}func (m *MyStruct) MarshalJSON() ([]byte, error) { // Here you do the marshalling of meta meta := `"Id":` + strconv.Itoa(m.meta.Id) // Manually calling Marshal for Contents cont, err := json.Marshal(m.Contents) if err != nil { return nil, err } // Stitching it all together return []byte(`{` + meta + `,"Contents":` + string(cont) + `}`), nil}func main() { str := &MyStruct{&meta{Id:42}, []interface{}{"MyForm", 12}} o, err := json.Marshal(str) if err != nil { panic(err) } fmt.Println(string(o))}{“ Id”:42,“ Contents”:[“ MyForm”,12]}
操场



