Browse Source

#63 fix Marshaler and Unmarshaler on struct

Tao Wen 8 years ago
parent
commit
839247df05
2 changed files with 29 additions and 2 deletions
  1. 10 2
      feature_reflect.go
  2. 19 0
      jsoniter_customize_test.go

+ 10 - 2
feature_reflect.go

@@ -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

+ 19 - 0
jsoniter_customize_test.go

@@ -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)
+}