From 565e07e45c3fff959ae82cfeff814309fe185928 Mon Sep 17 00:00:00 2001 From: Nao Yonashiro Date: Tue, 5 Jul 2022 01:15:08 +0900 Subject: [PATCH] fix: change isPtr to true on listElemCode fix #370 --- encode_test.go | 29 +++++++++++++++++++++++++++++ internal/encoder/compiler.go | 3 ++- 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/encode_test.go b/encode_test.go index 1c0de3c..480ec78 100644 --- a/encode_test.go +++ b/encode_test.go @@ -2424,3 +2424,32 @@ func TestIssue376(t *testing.T) { t.Errorf("unexpected result: %v != %v", got, expected) } } + +type Issue370 struct { + String string + Valid bool +} + +func (i *Issue370) MarshalJSON() ([]byte, error) { + if !i.Valid { + return json.Marshal(nil) + } + return json.Marshal(i.String) +} + +func TestIssue370(t *testing.T) { + v := []struct { + V Issue370 + }{ + {V: Issue370{String: "test", Valid: true}}, + } + b, err := json.Marshal(v) + if err != nil { + t.Fatal(err) + } + got := string(b) + expected := `[{"V":"test"}]` + if got != expected { + t.Errorf("unexpected result: %v != %v", got, expected) + } +} diff --git a/internal/encoder/compiler.go b/internal/encoder/compiler.go index de7323c..83eab57 100644 --- a/internal/encoder/compiler.go +++ b/internal/encoder/compiler.go @@ -487,7 +487,8 @@ func (c *Compiler) listElemCode(typ *runtime.Type) (Code, error) { case typ.Kind() == reflect.Map: return c.ptrCode(runtime.PtrTo(typ)) default: - code, err := c.typeToCodeWithPtr(typ, false) + // Strictly not isPtr == true, but reflect.ValueOf().Index() is canAddr, so set isPtr == true. + code, err := c.typeToCodeWithPtr(typ, true) if err != nil { return nil, err }