From 9f1239b90a7a48c5dc68a7eee08d8e1fba56db80 Mon Sep 17 00:00:00 2001 From: cuiweixie Date: Sat, 12 Feb 2022 15:19:18 +0000 Subject: [PATCH] math/big: produce valid JSON in Int.MarshalJSON when nil MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit Fixes #50940. Change-Id: Ie2a0c4505ca9d7e448017d9d00a020a6b3996be3 GitHub-Last-Rev: afd8c6b5598f43de25831c700b8d76cd97571426 GitHub-Pull-Request: golang/go#50941 Reviewed-on: https://go-review.googlesource.com/c/go/+/381963 Trust: Cherry Mui Reviewed-by: Emmanuel Odeke Trust: Emmanuel Odeke Run-TryBot: Emmanuel Odeke TryBot-Result: Gopher Robot Reviewed-by: Daniel Martí Trust: Daniel Martí --- src/math/big/intmarsh.go | 5 ++++- src/math/big/intmarsh_test.go | 14 ++++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/src/math/big/intmarsh.go b/src/math/big/intmarsh.go index c1422e2710..ce429ffc11 100644 --- a/src/math/big/intmarsh.go +++ b/src/math/big/intmarsh.go @@ -67,7 +67,10 @@ func (z *Int) UnmarshalText(text []byte) error { // MarshalJSON implements the json.Marshaler interface. func (x *Int) MarshalJSON() ([]byte, error) { - return x.MarshalText() + if x == nil { + return []byte("null"), nil + } + return x.abs.itoa(x.neg, 10), nil } // UnmarshalJSON implements the json.Unmarshaler interface. diff --git a/src/math/big/intmarsh_test.go b/src/math/big/intmarsh_test.go index f82956ceaf..936669b380 100644 --- a/src/math/big/intmarsh_test.go +++ b/src/math/big/intmarsh_test.go @@ -97,6 +97,20 @@ func TestIntJSONEncoding(t *testing.T) { } } + +func TestIntJSONEncodingNil(t *testing.T) { + var x *Int + b, err := x.MarshalJSON() + if err != nil { + t.Fatalf("marshaling of nil failed: %s", err) + } + got := string(b) + want := "null" + if got != want { + t.Fatalf("marshaling of nil failed: got %s want %s", got, want) + } +} + func TestIntXMLEncoding(t *testing.T) { for _, test := range encodingTests { for _, sign := range []string{"", "+", "-"} { -- 2.50.0