Skip to content

Commit 7dff82d

Browse files
author
Achille
authored
fix issue 28 (#29)
1 parent b37e66f commit 7dff82d

File tree

3 files changed

+32
-1
lines changed

3 files changed

+32
-1
lines changed

json/codec.go

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -156,7 +156,7 @@ func constructCodec(t reflect.Type, seen map[reflect.Type]*structType, canAddr b
156156
c = codec{encode: encoder.encodeString, decode: decoder.decodeString}
157157

158158
case reflect.Interface:
159-
c = codec{encode: encoder.encodeInterface, decode: constructMaybeEmptyInterfaceDecoderFunc(t)}
159+
c = constructInterfaceCodec(t)
160160

161161
case reflect.Array:
162162
c = constructArrayCodec(t, seen, canAddr)
@@ -711,6 +711,19 @@ func constructPointerDecodeFunc(t reflect.Type, decode decodeFunc) decodeFunc {
711711
}
712712
}
713713

714+
func constructInterfaceCodec(t reflect.Type) codec {
715+
return codec{
716+
encode: constructMaybeEmptyInterfaceEncoderFunc(t),
717+
decode: constructMaybeEmptyInterfaceDecoderFunc(t),
718+
}
719+
}
720+
721+
func constructMaybeEmptyInterfaceEncoderFunc(t reflect.Type) encodeFunc {
722+
return func(e encoder, b []byte, p unsafe.Pointer) ([]byte, error) {
723+
return e.encodeMaybeEmptyInterface(b, p, t)
724+
}
725+
}
726+
714727
func constructMaybeEmptyInterfaceDecoderFunc(t reflect.Type) decodeFunc {
715728
return func(d decoder, b []byte, p unsafe.Pointer) ([]byte, error) {
716729
return d.decodeMaybeEmptyInterface(b, p, t)

json/encode.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -592,6 +592,10 @@ func (e encoder) encodeInterface(b []byte, p unsafe.Pointer) ([]byte, error) {
592592
return Append(b, *(*interface{})(p), e.flags)
593593
}
594594

595+
func (e encoder) encodeMaybeEmptyInterface(b []byte, p unsafe.Pointer, t reflect.Type) ([]byte, error) {
596+
return Append(b, reflect.NewAt(t, p).Elem().Interface(), e.flags)
597+
}
598+
595599
func (e encoder) encodeUnsupportedTypeError(b []byte, p unsafe.Pointer, t reflect.Type) ([]byte, error) {
596600
return b, &UnsupportedTypeError{Type: t}
597601
}

json/json_test.go

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import (
55
"compress/gzip"
66
"encoding"
77
"encoding/json"
8+
"errors"
89
"flag"
910
"fmt"
1011
"io"
@@ -1475,3 +1476,16 @@ func TestGithubIssue26(t *testing.T) {
14751476
t.Error(err)
14761477
}
14771478
}
1479+
1480+
func TestGithubIssue28(t *testing.T) {
1481+
type A struct {
1482+
Err error `json:"err"`
1483+
}
1484+
1485+
if b, err := Marshal(&A{Err: errors.New("ABC")}); err != nil {
1486+
t.Error(err)
1487+
} else if string(b) != `{"err":{}}` {
1488+
t.Error(string(b))
1489+
}
1490+
1491+
}

0 commit comments

Comments
 (0)