jsoniter_enum_marshaler_test.go 800 B

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