Skip to content

Commit eef35e5

Browse files
authored
Merge pull request #169 from toffaletti/fix-nil-interface
Fix handling of nil empty interface
2 parents f8eb43e + 005d86d commit eef35e5

File tree

2 files changed

+21
-1
lines changed

2 files changed

+21
-1
lines changed

feature_reflect_native.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -373,7 +373,8 @@ func (codec *emptyInterfaceCodec) EncodeInterface(val interface{}, stream *Strea
373373
}
374374

375375
func (codec *emptyInterfaceCodec) IsEmpty(ptr unsafe.Pointer) bool {
376-
return ptr == nil
376+
emptyInterface := (*emptyInterface)(ptr)
377+
return emptyInterface.typ == nil
377378
}
378379

379380
type nonEmptyInterfaceCodec struct {

jsoniter_interface_test.go

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -351,3 +351,22 @@ func Test_nil_out_null_interface(t *testing.T) {
351351
should.Equal(nil, err)
352352
should.Equal(nil, obj2.Field)
353353
}
354+
355+
func Test_omitempty_nil_interface(t *testing.T) {
356+
type TestData struct {
357+
Field interface{} `json:"field,omitempty"`
358+
}
359+
should := require.New(t)
360+
361+
obj := TestData{
362+
Field: nil,
363+
}
364+
365+
js, err := json.Marshal(obj)
366+
should.Equal(nil, err)
367+
should.Equal("{}", string(js))
368+
369+
str, err := MarshalToString(obj)
370+
should.Equal(nil, err)
371+
should.Equal(string(js), str)
372+
}

0 commit comments

Comments
 (0)