Selaa lähdekoodia

#156 invoke Marshaler defined on pointer types

Tao Wen 8 vuotta sitten
vanhempi
commit
d80309af3b
2 muutettua tiedostoa jossa 37 lisäystä ja 0 poistoa
  1. 13 0
      feature_reflect.go
  2. 24 0
      jsoniter_customize_test.go

+ 13 - 0
feature_reflect.go

@@ -466,6 +466,19 @@ func createEncoderOfType(cfg *frozenConfig, typ reflect.Type) (ValEncoder, error
 		}
 		return encoder, nil
 	}
+	if reflect.PtrTo(typ).Implements(marshalerType) {
+		checkIsEmpty, err := createCheckIsEmpty(reflect.PtrTo(typ))
+		if err != nil {
+			return nil, err
+		}
+		templateInterface := reflect.New(typ).Interface()
+		var encoder ValEncoder = &marshalerEncoder{
+			templateInterface: extractInterface(templateInterface),
+			checkIsEmpty:      checkIsEmpty,
+		}
+		encoder = &optionalEncoder{encoder}
+		return encoder, nil
+	}
 	if typ.Implements(textMarshalerType) {
 		checkIsEmpty, err := createCheckIsEmpty(typ)
 		if err != nil {

+ 24 - 0
jsoniter_customize_test.go

@@ -314,3 +314,27 @@ func Test_recursive_empty_interface_customization(t *testing.T) {
 	Unmarshal([]byte("[100]"), &obj)
 	should.Equal([]interface{}{int64(100)}, obj)
 }
+
+type GeoLocation struct {
+	Id             string     `json:"id,omitempty" db:"id"`
+}
+
+func (p *GeoLocation) MarshalJSON() ([]byte, error) {
+	return []byte(`{}`), nil
+}
+
+func (p *GeoLocation) UnmarshalJSON(input []byte) error {
+	p.Id = "hello"
+	return nil
+}
+
+func Test_marshal_and_unmarshal_on_non_pointer(t *testing.T) {
+	should := require.New(t)
+	locations := []GeoLocation{{"000"}}
+	bytes, err := Marshal(locations)
+	should.Nil(err)
+	should.Equal("[{}]", string(bytes))
+	err = Unmarshal([]byte("[1]"), &locations)
+	should.Nil(err)
+	should.Equal("hello", locations[0].Id)
+}