From c39a632e65c5b49bff7452272de34455fcc4e458 Mon Sep 17 00:00:00 2001 From: Tao Wen Date: Thu, 25 Jan 2018 14:47:50 +0800 Subject: [PATCH] fix #227, fix empty json.Number --- feature_reflect_native.go | 28 ++++++++++++++++++++++++---- jsoniter_int_test.go | 6 ++++++ 2 files changed, 30 insertions(+), 4 deletions(-) diff --git a/feature_reflect_native.go b/feature_reflect_native.go index 5faa682..464a8f7 100644 --- a/feature_reflect_native.go +++ b/feature_reflect_native.go @@ -458,11 +458,21 @@ func (codec *jsonNumberCodec) Decode(ptr unsafe.Pointer, iter *Iterator) { } func (codec *jsonNumberCodec) Encode(ptr unsafe.Pointer, stream *Stream) { - stream.WriteRaw(string(*((*json.Number)(ptr)))) + number := *((*json.Number)(ptr)) + if len(number) == 0 { + stream.WriteRaw("0") + } else { + stream.WriteRaw(string(number)) + } } func (codec *jsonNumberCodec) EncodeInterface(val interface{}, stream *Stream) { - stream.WriteRaw(string(val.(json.Number))) + number := val.(json.Number) + if len(number) == 0 { + stream.WriteRaw("0") + } else { + stream.WriteRaw(string(number)) + } } func (codec *jsonNumberCodec) IsEmpty(ptr unsafe.Pointer) bool { @@ -485,11 +495,21 @@ func (codec *jsoniterNumberCodec) Decode(ptr unsafe.Pointer, iter *Iterator) { } func (codec *jsoniterNumberCodec) Encode(ptr unsafe.Pointer, stream *Stream) { - stream.WriteRaw(string(*((*Number)(ptr)))) + number := *((*Number)(ptr)) + if len(number) == 0 { + stream.WriteRaw("0") + } else { + stream.WriteRaw(string(number)) + } } func (codec *jsoniterNumberCodec) EncodeInterface(val interface{}, stream *Stream) { - stream.WriteRaw(string(val.(Number))) + number := val.(Number) + if len(number) == 0 { + stream.WriteRaw("0") + } else { + stream.WriteRaw(string(number)) + } } func (codec *jsoniterNumberCodec) IsEmpty(ptr unsafe.Pointer) bool { diff --git a/jsoniter_int_test.go b/jsoniter_int_test.go index 378947c..e0f1183 100644 --- a/jsoniter_int_test.go +++ b/jsoniter_int_test.go @@ -524,10 +524,16 @@ func Test_null_as_number(t *testing.T) { err := json.Unmarshal([]byte(`null`), &v1) should.Nil(err) should.Equal("", string(v1)) + output, err := json.Marshal(v1) + should.NoError(err) + should.Equal("0", string(output)) var v2 Number err = Unmarshal([]byte(`null`), &v2) should.Nil(err) should.Equal("", string(v2)) + output, err = Marshal(v2) + should.NoError(err) + should.Equal("0", string(output)) } func Test_float_as_int(t *testing.T) {