Selaa lähdekoodia

RegisterTypeEncoder and RegisterTypeDecoder should have higher priority

Tao Wen 8 vuotta sitten
vanhempi
commit
f20f74519d
2 muutettua tiedostoa jossa 51 lisäystä ja 0 poistoa
  1. 12 0
      feature_reflect.go
  2. 39 0
      jsoniter_customize_test.go

+ 12 - 0
feature_reflect.go

@@ -300,6 +300,12 @@ func decoderOfType(typ reflect.Type) (Decoder, error) {
 	if typeDecoder != nil {
 		return typeDecoder, nil
 	}
+	if typ.Kind() == reflect.Ptr {
+		typeDecoder := typeDecoders[typ.Elem().String()]
+		if typeDecoder != nil {
+			return &optionalDecoder{typ.Elem(),typeDecoder}, nil
+		}
+	}
 	cacheKey := typ
 	cachedDecoder := getDecoderFromCache(cacheKey)
 	if cachedDecoder != nil {
@@ -375,6 +381,12 @@ func encoderOfType(typ reflect.Type) (Encoder, error) {
 	if typeEncoder != nil {
 		return typeEncoder, nil
 	}
+	if typ.Kind() == reflect.Ptr {
+		typeEncoder := typeEncoders[typ.Elem().String()]
+		if typeEncoder != nil {
+			return &optionalEncoder{typeEncoder}, nil
+		}
+	}
 	cacheKey := typ
 	cachedEncoder := getEncoderFromCache(cacheKey)
 	if cachedEncoder != nil {

+ 39 - 0
jsoniter_customize_test.go

@@ -151,6 +151,24 @@ func Test_marshaler(t *testing.T) {
 	should.Equal(`{"Field":"hello"}`, str)
 }
 
+func Test_marshaler_and_encoder(t *testing.T) {
+	type TestObject struct {
+		Field *ObjectImplementedMarshaler
+	}
+	should := require.New(t)
+	RegisterTypeEncoder("jsoniter.ObjectImplementedMarshaler", func(ptr unsafe.Pointer, stream *Stream) {
+		stream.WriteString("hello from encoder")
+	})
+	val := ObjectImplementedMarshaler(100)
+	obj := TestObject{&val}
+	bytes, err := json.Marshal(obj)
+	should.Nil(err)
+	should.Equal(`{"Field":"hello"}`, string(bytes))
+	str, err := MarshalToString(obj)
+	should.Nil(err)
+	should.Equal(`{"Field":"hello from encoder"}`, str)
+}
+
 type ObjectImplementedUnmarshaler int
 
 func (obj *ObjectImplementedUnmarshaler) UnmarshalJSON([]byte) error {
@@ -174,3 +192,24 @@ func Test_unmarshaler(t *testing.T) {
 	should.Nil(err)
 	should.Equal(100, int(*obj.Field))
 }
+
+func Test_unmarshaler_and_decoder(t *testing.T) {
+	type TestObject struct {
+		Field *ObjectImplementedUnmarshaler
+		Field2 string
+	}
+	should := require.New(t)
+	RegisterTypeDecoder("jsoniter.ObjectImplementedUnmarshaler", func(ptr unsafe.Pointer, iter *Iterator) {
+		*(*ObjectImplementedUnmarshaler)(ptr) = 10
+		iter.Skip()
+	})
+	obj := TestObject{}
+	val := ObjectImplementedUnmarshaler(0)
+	obj.Field = &val
+	err := json.Unmarshal([]byte(`{"Field":"hello"}`), &obj)
+	should.Nil(err)
+	should.Equal(100, int(*obj.Field))
+	err = Unmarshal([]byte(`{"Field":"hello"}`), &obj)
+	should.Nil(err)
+	should.Equal(10, int(*obj.Field))
+}