aboutsummaryrefslogtreecommitdiff
path: root/src/encoding/json/encode_test.go
diff options
context:
space:
mode:
Diffstat (limited to 'src/encoding/json/encode_test.go')
-rw-r--r--src/encoding/json/encode_test.go31
1 files changed, 24 insertions, 7 deletions
diff --git a/src/encoding/json/encode_test.go b/src/encoding/json/encode_test.go
index daab713766..18a92bae7c 100644
--- a/src/encoding/json/encode_test.go
+++ b/src/encoding/json/encode_test.go
@@ -6,6 +6,7 @@ package json
import (
"bytes"
+ "encoding"
"fmt"
"log"
"math"
@@ -453,18 +454,31 @@ type BugX struct {
BugB
}
-// Issue 16042. Even if a nil interface value is passed in
-// as long as it implements MarshalJSON, it should be marshaled.
-type nilMarshaler string
+// golang.org/issue/16042.
+// Even if a nil interface value is passed in, as long as
+// it implements Marshaler, it should be marshaled.
+type nilJSONMarshaler string
-func (nm *nilMarshaler) MarshalJSON() ([]byte, error) {
+func (nm *nilJSONMarshaler) MarshalJSON() ([]byte, error) {
if nm == nil {
return Marshal("0zenil0")
}
return Marshal("zenil:" + string(*nm))
}
-// Issue 16042.
+// golang.org/issue/34235.
+// Even if a nil interface value is passed in, as long as
+// it implements encoding.TextMarshaler, it should be marshaled.
+type nilTextMarshaler string
+
+func (nm *nilTextMarshaler) MarshalText() ([]byte, error) {
+ if nm == nil {
+ return []byte("0zenil0"), nil
+ }
+ return []byte("zenil:" + string(*nm)), nil
+}
+
+// See golang.org/issue/16042 and golang.org/issue/34235.
func TestNilMarshal(t *testing.T) {
testCases := []struct {
v interface{}
@@ -478,8 +492,11 @@ func TestNilMarshal(t *testing.T) {
{v: []byte(nil), want: `null`},
{v: struct{ M string }{"gopher"}, want: `{"M":"gopher"}`},
{v: struct{ M Marshaler }{}, want: `{"M":null}`},
- {v: struct{ M Marshaler }{(*nilMarshaler)(nil)}, want: `{"M":"0zenil0"}`},
- {v: struct{ M interface{} }{(*nilMarshaler)(nil)}, want: `{"M":null}`},
+ {v: struct{ M Marshaler }{(*nilJSONMarshaler)(nil)}, want: `{"M":"0zenil0"}`},
+ {v: struct{ M interface{} }{(*nilJSONMarshaler)(nil)}, want: `{"M":null}`},
+ {v: struct{ M encoding.TextMarshaler }{}, want: `{"M":null}`},
+ {v: struct{ M encoding.TextMarshaler }{(*nilTextMarshaler)(nil)}, want: `{"M":"0zenil0"}`},
+ {v: struct{ M interface{} }{(*nilTextMarshaler)(nil)}, want: `{"M":null}`},
}
for _, tt := range testCases {