diff --git a/gen/decoder.go b/gen/decoder.go index bafa162..8a7afbd 100644 --- a/gen/decoder.go +++ b/gen/decoder.go @@ -212,8 +212,13 @@ func (g *Generator) genTypeDecoderNoCheck(t reflect.Type, out string, tags field if t.NumMethod() != 0 { return fmt.Errorf("interface type %v not supported: only interface{} is allowed", t) } - fmt.Fprintln(g.out, ws+out+" = in.Interface()") - + fmt.Fprintln(g.out, ws+"if m, ok := "+out+".(easyjson.Unmarshaler); ok {") + fmt.Fprintln(g.out, ws+"m.UnmarshalEasyJSON(in)") + fmt.Fprintln(g.out, ws+"} else if m, ok := "+out+".(json.Unmarshaler); ok {") + fmt.Fprintln(g.out, ws+"m.UnmarshalJSON(in.Raw())") + fmt.Fprintln(g.out, ws+"} else {") + fmt.Fprintln(g.out, ws+" "+out+" = in.Interface()") + fmt.Fprintln(g.out, ws+"}") default: return fmt.Errorf("don't know how to decode %v", t) } diff --git a/gen/generator.go b/gen/generator.go index 32e806e..c5c9103 100644 --- a/gen/generator.go +++ b/gen/generator.go @@ -15,7 +15,7 @@ import ( const pkgWriter = "github.com/mailru/easyjson/jwriter" const pkgLexer = "github.com/mailru/easyjson/jlexer" -const pkgEasyjson = "github.com/mailru/easyjson" +const pkgEasyJSON = "github.com/mailru/easyjson" // FieldNamer defines a policy for generating names for struct fields. type FieldNamer interface { @@ -60,7 +60,7 @@ func NewGenerator(filename string) *Generator { imports: map[string]string{ pkgWriter: "jwriter", pkgLexer: "jlexer", - pkgEasyjson: "easyjson", + pkgEasyJSON: "easyjson", "encoding/json": "json", }, fieldNamer: DefaultFieldNamer{}, diff --git a/tests/basic_test.go b/tests/basic_test.go index 25b1bfc..5798ee4 100644 --- a/tests/basic_test.go +++ b/tests/basic_test.go @@ -206,3 +206,15 @@ func TestNestedEasyJsonMarshal(t *testing.T) { } } } + +func TestUnmarshalStructWithEmbeddedPtrStruct(t *testing.T) { + var s = StructWithInterface{Field2: &EmbeddedStruct{}} + var err error + err = easyjson.Unmarshal([]byte(structWithInterfaceString), &s) + if err != nil { + t.Errorf("easyjson.Unmarshal() error: %v", err) + } + if !reflect.DeepEqual(s, structWithInterfaceValueFilled) { + t.Errorf("easyjson.Unmarshal() = %#v; want %#v", s, structWithInterfaceValueFilled) + } +} diff --git a/tests/data.go b/tests/data.go index a46a4a5..b13bcd8 100644 --- a/tests/data.go +++ b/tests/data.go @@ -634,3 +634,17 @@ type EncodingFlagsTestMap struct { type EncodingFlagsTestSlice struct { F []string } + +type StructWithInterface struct { + Field1 int `json:"f1"` + Field2 interface{} `json:"f2"` + Field3 string `json:"f3"` +} + +type EmbeddedStruct struct { + Field1 int `json:"f1"` + Field2 string `json:"f2"` +} + +var structWithInterfaceString = `{"f1":1,"f2":{"f1":11,"f2":"22"},"f3":"3"}` +var structWithInterfaceValueFilled = StructWithInterface{1, &EmbeddedStruct{11, "22"}, "3"}