You've already forked json-iterator
							
							
				mirror of
				https://github.com/json-iterator/go.git
				synced 2025-10-31 00:07:40 +02:00 
			
		
		
		
	#156 invoke Marshaler defined on pointer types
This commit is contained in:
		| @@ -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 { | ||||
|   | ||||
| @@ -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) | ||||
| } | ||||
		Reference in New Issue
	
	Block a user