You've already forked json-iterator
							
							
				mirror of
				https://github.com/json-iterator/go.git
				synced 2025-10-31 00:07:40 +02:00 
			
		
		
		
	When MarshalJSON was defined on a pointer receiver custom enum type marshaling/unmarshaling was panicing since the underlying primitive type was treated as a pointer. Since method set for pointer receivers includes value receiver methods we don't really need optionalEncoder and can just use marshalEncoder directly.
		
			
				
	
	
		
			51 lines
		
	
	
		
			806 B
		
	
	
	
		
			Go
		
	
	
	
	
	
			
		
		
	
	
			51 lines
		
	
	
		
			806 B
		
	
	
	
		
			Go
		
	
	
	
	
	
| 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)
 | |
| }
 |