1
0
mirror of https://github.com/json-iterator/go.git synced 2025-02-01 19:14:29 +02:00

#63 fix Marshaler and Unmarshaler on struct

This commit is contained in:
Tao Wen 2017-06-20 07:23:22 +08:00
parent f5edf564c8
commit 839247df05
2 changed files with 29 additions and 2 deletions

View File

@ -306,7 +306,11 @@ func createDecoderOfType(cfg *frozenConfig, typ reflect.Type) (Decoder, error) {
}
if typ.ConvertibleTo(unmarshalerType) {
templateInterface := reflect.New(typ).Elem().Interface()
return &optionalDecoder{typ, &unmarshalerDecoder{extractInterface(templateInterface)}}, nil
var decoder Decoder = &unmarshalerDecoder{extractInterface(templateInterface)}
if typ.Kind() != reflect.Struct {
decoder = &optionalDecoder{typ, decoder}
}
return decoder, nil
}
if typ.ConvertibleTo(anyType) {
return &anyCodec{}, nil
@ -401,7 +405,11 @@ func createEncoderOfType(cfg *frozenConfig, typ reflect.Type) (Encoder, error) {
}
if typ.ConvertibleTo(marshalerType) {
templateInterface := reflect.New(typ).Elem().Interface()
return &optionalEncoder{&marshalerEncoder{extractInterface(templateInterface)}}, nil
var encoder Encoder = &marshalerEncoder{extractInterface(templateInterface)}
if typ.Kind() != reflect.Struct {
encoder = &optionalEncoder{encoder}
}
return encoder, nil
}
if typ.ConvertibleTo(anyType) {
return &anyCodec{}, nil

View File

@ -213,3 +213,22 @@ func Test_unmarshaler_and_decoder(t *testing.T) {
should.Nil(err)
should.Equal(10, int(*obj.Field))
}
type tmString string
type tmStruct struct {
String tmString
}
func (s tmStruct) MarshalJSON() ([]byte, error) {
var b []byte
b = append(b, '"')
b = append(b, s.String...)
b = append(b, '"')
return b, nil
}
func Test_marshaler_on_struct(t *testing.T) {
fixed := tmStruct{"hello"}
//json.Marshal(fixed)
Marshal(fixed)
}