mirror of
https://github.com/json-iterator/go.git
synced 2025-04-23 11:37:32 +02:00
Merge pull request #170 from olegshaldybin/marshal-enum-pointer
Fix custom marshaler for enum types
This commit is contained in:
commit
92772579dd
@ -476,7 +476,6 @@ func createEncoderOfType(cfg *frozenConfig, typ reflect.Type) (ValEncoder, error
|
|||||||
templateInterface: extractInterface(templateInterface),
|
templateInterface: extractInterface(templateInterface),
|
||||||
checkIsEmpty: checkIsEmpty,
|
checkIsEmpty: checkIsEmpty,
|
||||||
}
|
}
|
||||||
encoder = &optionalEncoder{encoder}
|
|
||||||
return encoder, nil
|
return encoder, nil
|
||||||
}
|
}
|
||||||
if typ.Implements(textMarshalerType) {
|
if typ.Implements(textMarshalerType) {
|
||||||
|
@ -661,6 +661,7 @@ func (encoder *marshalerEncoder) Encode(ptr unsafe.Pointer, stream *Stream) {
|
|||||||
templateInterface.word = ptr
|
templateInterface.word = ptr
|
||||||
realInterface := (*interface{})(unsafe.Pointer(&templateInterface))
|
realInterface := (*interface{})(unsafe.Pointer(&templateInterface))
|
||||||
marshaler := (*realInterface).(json.Marshaler)
|
marshaler := (*realInterface).(json.Marshaler)
|
||||||
|
|
||||||
bytes, err := marshaler.MarshalJSON()
|
bytes, err := marshaler.MarshalJSON()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
stream.Error = err
|
stream.Error = err
|
||||||
|
50
jsoniter_enum_marshaler_test.go
Normal file
50
jsoniter_enum_marshaler_test.go
Normal file
@ -0,0 +1,50 @@
|
|||||||
|
package jsoniter
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
)
|
||||||
|
|
||||||
|
type MyEnum int64
|
||||||
|
|
||||||
|
const (
|
||||||
|
MyEnumA MyEnum = iota
|
||||||
|
MyEnumB
|
||||||
|
)
|
||||||
|
|
||||||
|
func (m *MyEnum) MarshalJSON() ([]byte, error) {
|
||||||
|
return []byte(fmt.Sprintf(`"foo-%d"`, int(*m))), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *MyEnum) UnmarshalJSON(jb []byte) error {
|
||||||
|
switch string(jb) {
|
||||||
|
case `"foo-1"`:
|
||||||
|
*m = MyEnumB
|
||||||
|
default:
|
||||||
|
*m = MyEnumA
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func Test_custom_marshaler_on_enum(t *testing.T) {
|
||||||
|
type Wrapper struct {
|
||||||
|
Payload interface{}
|
||||||
|
}
|
||||||
|
type Wrapper2 struct {
|
||||||
|
Payload MyEnum
|
||||||
|
}
|
||||||
|
should := require.New(t)
|
||||||
|
|
||||||
|
w := Wrapper{Payload: MyEnumB}
|
||||||
|
|
||||||
|
jb, err := Marshal(w)
|
||||||
|
should.Equal(nil, err)
|
||||||
|
should.Equal(`{"Payload":"foo-1"}`, string(jb))
|
||||||
|
|
||||||
|
var w2 Wrapper2
|
||||||
|
err = Unmarshal(jb, &w2)
|
||||||
|
should.Equal(nil, err)
|
||||||
|
should.Equal(MyEnumB, w2.Payload)
|
||||||
|
}
|
Loading…
x
Reference in New Issue
Block a user