Skip to content

Commit d80309a

Browse files
committed
#156 invoke Marshaler defined on pointer types
1 parent 36b1496 commit d80309a

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

feature_reflect.go

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -466,6 +466,19 @@ func createEncoderOfType(cfg *frozenConfig, typ reflect.Type) (ValEncoder, error
466466
}
467467
return encoder, nil
468468
}
469+
if reflect.PtrTo(typ).Implements(marshalerType) {
470+
checkIsEmpty, err := createCheckIsEmpty(reflect.PtrTo(typ))
471+
if err != nil {
472+
return nil, err
473+
}
474+
templateInterface := reflect.New(typ).Interface()
475+
var encoder ValEncoder = &marshalerEncoder{
476+
templateInterface: extractInterface(templateInterface),
477+
checkIsEmpty: checkIsEmpty,
478+
}
479+
encoder = &optionalEncoder{encoder}
480+
return encoder, nil
481+
}
469482
if typ.Implements(textMarshalerType) {
470483
checkIsEmpty, err := createCheckIsEmpty(typ)
471484
if err != nil {

jsoniter_customize_test.go

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -314,3 +314,27 @@ func Test_recursive_empty_interface_customization(t *testing.T) {
314314
Unmarshal([]byte("[100]"), &obj)
315315
should.Equal([]interface{}{int64(100)}, obj)
316316
}
317+
318+
type GeoLocation struct {
319+
Id string `json:"id,omitempty" db:"id"`
320+
}
321+
322+
func (p *GeoLocation) MarshalJSON() ([]byte, error) {
323+
return []byte(`{}`), nil
324+
}
325+
326+
func (p *GeoLocation) UnmarshalJSON(input []byte) error {
327+
p.Id = "hello"
328+
return nil
329+
}
330+
331+
func Test_marshal_and_unmarshal_on_non_pointer(t *testing.T) {
332+
should := require.New(t)
333+
locations := []GeoLocation{{"000"}}
334+
bytes, err := Marshal(locations)
335+
should.Nil(err)
336+
should.Equal("[{}]", string(bytes))
337+
err = Unmarshal([]byte("[1]"), &locations)
338+
should.Nil(err)
339+
should.Equal("hello", locations[0].Id)
340+
}

0 commit comments

Comments
 (0)