Skip to content

Commit 9277257

Browse files
authored
Merge pull request #170 from olegshaldybin/marshal-enum-pointer
Fix custom marshaler for enum types
2 parents eef35e5 + ae57d16 commit 9277257

File tree

3 files changed

+51
-1
lines changed

3 files changed

+51
-1
lines changed

feature_reflect.go

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -476,7 +476,6 @@ func createEncoderOfType(cfg *frozenConfig, typ reflect.Type) (ValEncoder, error
476476
templateInterface: extractInterface(templateInterface),
477477
checkIsEmpty: checkIsEmpty,
478478
}
479-
encoder = &optionalEncoder{encoder}
480479
return encoder, nil
481480
}
482481
if typ.Implements(textMarshalerType) {

feature_reflect_native.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -661,6 +661,7 @@ func (encoder *marshalerEncoder) Encode(ptr unsafe.Pointer, stream *Stream) {
661661
templateInterface.word = ptr
662662
realInterface := (*interface{})(unsafe.Pointer(&templateInterface))
663663
marshaler := (*realInterface).(json.Marshaler)
664+
664665
bytes, err := marshaler.MarshalJSON()
665666
if err != nil {
666667
stream.Error = err

jsoniter_enum_marshaler_test.go

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
package jsoniter
2+
3+
import (
4+
"fmt"
5+
"testing"
6+
7+
"github.com/stretchr/testify/require"
8+
)
9+
10+
type MyEnum int64
11+
12+
const (
13+
MyEnumA MyEnum = iota
14+
MyEnumB
15+
)
16+
17+
func (m *MyEnum) MarshalJSON() ([]byte, error) {
18+
return []byte(fmt.Sprintf(`"foo-%d"`, int(*m))), nil
19+
}
20+
21+
func (m *MyEnum) UnmarshalJSON(jb []byte) error {
22+
switch string(jb) {
23+
case `"foo-1"`:
24+
*m = MyEnumB
25+
default:
26+
*m = MyEnumA
27+
}
28+
return nil
29+
}
30+
31+
func Test_custom_marshaler_on_enum(t *testing.T) {
32+
type Wrapper struct {
33+
Payload interface{}
34+
}
35+
type Wrapper2 struct {
36+
Payload MyEnum
37+
}
38+
should := require.New(t)
39+
40+
w := Wrapper{Payload: MyEnumB}
41+
42+
jb, err := Marshal(w)
43+
should.Equal(nil, err)
44+
should.Equal(`{"Payload":"foo-1"}`, string(jb))
45+
46+
var w2 Wrapper2
47+
err = Unmarshal(jb, &w2)
48+
should.Equal(nil, err)
49+
should.Equal(MyEnumB, w2.Payload)
50+
}

0 commit comments

Comments
 (0)