Implement json marshaller over an inline element in Go

I have a structure that I would like to efficiently encode JSON:

type MyStruct struct { *Meta Contents []interface{} } type Meta struct { Id int } 

The structure contains metadata of a known form and contents of an unknown form. The content list is populated at run time, so I really don't control them. To improve the speed of sorting Go, I would like to implement the Marshaller interface over the Meta structure. The Marshaller interface is as follows:

 type Marshaler interface { MarshalJSON() ([]byte, error) } 

Please keep in mind that the meta structure is not as simple as shown here. I tried to implement the Marshaler interface over the Meta structure, but it seems that when I then JSON marshal MyStruct, the result will be only the result returned by the Meta marshalling interface.

So my question is: how can I create a JSON structure containing an inline structure with my own JSON marshaller and another structure without one?

+4
source share
1 answer

Since the MarshalJSON method of the anonymous *Meta field will be upgraded to MyStruct , the encoding/json package will use this method when MyStruct is configured.

What you can do, instead of letting Meta implement the Marshaller interface, you can implement the interface in MyStruct as follows:

 package main import ( "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)) } 

{"Identifier": 42, "Contents": ["MyForm", 12]}

Playground

+4
source

Source: https://habr.com/ru/post/1499750/


All Articles