json-iterator / go

A high-performance 100% compatible drop-in replacement of "encoding/json"
http://jsoniter.com/migrate-from-go-std.html
MIT License
13.34k stars 1.02k forks source link

Anonymous field does not handle typeEncoders/typeDecoders #634

Open molon opened 2 years ago

molon commented 2 years ago

https://github.com/json-iterator/go/blob/e6b9536d3649bda3e8842bb7e4fab489d79a97ea/reflect_extension.go#L348-L375

func TestAnonymous(t *testing.T) {
    type Body struct {
        Content string `json:"content"`
    }

    type Wrapper struct {
        *Body
        Other string `json:"other"`
    }

    jsoniter.RegisterTypeEncoderFunc("Body",
        func(ptr unsafe.Pointer, stream *jsoniter.Stream) {
            stream.WriteObjectStart()
            stream.WriteObjectField("content")
            stream.WriteString(((*Body)(ptr)).Content + "-fixed")
            stream.WriteObjectEnd()
        },
        func(unsafe.Pointer) bool {
            return false
        },
    )
    w := Wrapper{
        Body: &Body{
            Content: "contentx",
        },
        Other: "otherx",
    }
    jsn, err := jsoniter.Marshal(w.Body)
    if err != nil {
        t.Fatal(err)
    }
    assert.Equal(t, `{"content":"contentx-fixed"}`, string(jsn))

    jsn, err = jsoniter.Marshal(w)
    if err != nil {
        t.Fatal(err)
    }
    // !!! assert failed here
    assert.Equal(t, `{"content":"contentx-fixed","other":"otherx"}`, string(jsn))
}