Skip to content

Commit 5d7fea6

Browse files
committed
fix json-iterator#308 do NOT skip embedded structs without tag when OnlyTaggedField is set to true
1 parent 9ec4cb8 commit 5d7fea6

File tree

2 files changed

+56
-1
lines changed

2 files changed

+56
-1
lines changed

api_tests/config_test.go

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -172,3 +172,58 @@ func Test_CaseSensitive_MoreThanTenFields(t *testing.T) {
172172
should.Equal(tc.expectedOutput, output)
173173
}
174174
}
175+
176+
type onlyTaggedFieldStruct struct {
177+
A string `json:"a"`
178+
B string
179+
FSimpl F `json:"f_simpl"`
180+
ISimpl I
181+
FPtr *F `json:"f_ptr"`
182+
IPtr *I
183+
F
184+
*I
185+
}
186+
187+
type F struct {
188+
G string `json:"g"`
189+
H string
190+
}
191+
192+
type I struct {
193+
J string `json:"j"`
194+
K string
195+
}
196+
197+
func Test_OnlyTaggedField(t *testing.T) {
198+
should := require.New(t)
199+
200+
obj := onlyTaggedFieldStruct{
201+
A: "a",
202+
B: "b",
203+
FSimpl: F{G: "g", H: "h"},
204+
ISimpl: I{J: "j", K: "k"},
205+
FPtr: &F{G: "g", H: "h"},
206+
IPtr: &I{J: "j", K: "k"},
207+
F: F{G: "g", H: "h"},
208+
I: &I{J: "j", K: "k"},
209+
}
210+
211+
output, err := jsoniter.Config{OnlyTaggedField: true}.Froze().Marshal(obj)
212+
should.Nil(err)
213+
214+
m := make(map[string]interface{})
215+
err = jsoniter.Unmarshal(output, &m)
216+
should.Nil(err)
217+
218+
should.Equal(map[string]interface{}{
219+
"a": "a",
220+
"f_simpl": map[string]interface{}{
221+
"g": "g",
222+
},
223+
"f_ptr": map[string]interface{}{
224+
"g": "g",
225+
},
226+
"g": "g",
227+
"j": "j",
228+
}, m)
229+
}

reflect_extension.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -338,7 +338,7 @@ func describeStruct(ctx *ctx, typ reflect2.Type) *StructDescriptor {
338338
for i := 0; i < structType.NumField(); i++ {
339339
field := structType.Field(i)
340340
tag, hastag := field.Tag().Lookup(ctx.getTagKey())
341-
if ctx.onlyTaggedField && !hastag {
341+
if ctx.onlyTaggedField && !hastag && !field.Anonymous() {
342342
continue
343343
}
344344
tagParts := strings.Split(tag, ",")

0 commit comments

Comments
 (0)