go icon indicating copy to clipboard operation
go copied to clipboard

Anonymous field does not handle typeEncoders/typeDecoders

Open molon opened this issue 3 years ago • 0 comments

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))
}

molon avatar Sep 11 '22 22:09 molon