package test import ( "unsafe" "strconv" "testing" "github.com/stretchr/testify/require" "github.com/json-iterator/go" ) type TestObject1 struct { Field1 string } type testExtension struct { jsoniter.DummyExtension } func (extension *testExtension) UpdateStructDescriptor(structDescriptor *jsoniter.StructDescriptor) { if structDescriptor.Type.String() != "test.TestObject1" { return } binding := structDescriptor.GetField("Field1") binding.Encoder = &funcEncoder{fun: func(ptr unsafe.Pointer, stream *jsoniter.Stream) { str := *((*string)(ptr)) val, _ := strconv.Atoi(str) stream.WriteInt(val) }} binding.Decoder = &funcDecoder{func(ptr unsafe.Pointer, iter *jsoniter.Iterator) { *((*string)(ptr)) = strconv.Itoa(iter.ReadInt()) }} binding.ToNames = []string{"field-1"} binding.FromNames = []string{"field-1"} } func Test_customize_field_by_extension(t *testing.T) { should := require.New(t) cfg := jsoniter.Config{}.Froze() cfg.RegisterExtension(&testExtension{}) obj := TestObject1{} err := cfg.UnmarshalFromString(`{"field-1": 100}`, &obj) should.Nil(err) should.Equal("100", obj.Field1) str, err := cfg.MarshalToString(obj) should.Nil(err) should.Equal(`{"field-1":100}`, str) } type funcDecoder struct { fun jsoniter.DecoderFunc } func (decoder *funcDecoder) Decode(ptr unsafe.Pointer, iter *jsoniter.Iterator) { decoder.fun(ptr, iter) } type funcEncoder struct { fun jsoniter.EncoderFunc isEmptyFunc func(ptr unsafe.Pointer) bool } func (encoder *funcEncoder) Encode(ptr unsafe.Pointer, stream *jsoniter.Stream) { encoder.fun(ptr, stream) } func (encoder *funcEncoder) EncodeInterface(val interface{}, stream *jsoniter.Stream) { jsoniter.WriteToStream(val, stream, encoder) } func (encoder *funcEncoder) IsEmpty(ptr unsafe.Pointer) bool { if encoder.isEmptyFunc == nil { return false } return encoder.isEmptyFunc(ptr) }