@@ -6,6 +6,7 @@ package json
6
6
7
7
import (
8
8
"bytes"
9
+ "encoding"
9
10
"fmt"
10
11
"log"
11
12
"math"
@@ -453,18 +454,31 @@ type BugX struct {
453
454
BugB
454
455
}
455
456
456
- // Issue 16042. Even if a nil interface value is passed in
457
- // as long as it implements MarshalJSON, it should be marshaled.
458
- type nilMarshaler string
457
+ // golang.org/issue/16042.
458
+ // Even if a nil interface value is passed in, as long as
459
+ // it implements Marshaler, it should be marshaled.
460
+ type nilJSONMarshaler string
459
461
460
- func (nm * nilMarshaler ) MarshalJSON () ([]byte , error ) {
462
+ func (nm * nilJSONMarshaler ) MarshalJSON () ([]byte , error ) {
461
463
if nm == nil {
462
464
return Marshal ("0zenil0" )
463
465
}
464
466
return Marshal ("zenil:" + string (* nm ))
465
467
}
466
468
467
- // Issue 16042.
469
+ // golang.org/issue/34235.
470
+ // Even if a nil interface value is passed in, as long as
471
+ // it implements encoding.TextMarshaler, it should be marshaled.
472
+ type nilTextMarshaler string
473
+
474
+ func (nm * nilTextMarshaler ) MarshalText () ([]byte , error ) {
475
+ if nm == nil {
476
+ return []byte ("0zenil0" ), nil
477
+ }
478
+ return []byte ("zenil:" + string (* nm )), nil
479
+ }
480
+
481
+ // See golang.org/issue/16042 and golang.org/issue/34235.
468
482
func TestNilMarshal (t * testing.T ) {
469
483
testCases := []struct {
470
484
v interface {}
@@ -478,8 +492,11 @@ func TestNilMarshal(t *testing.T) {
478
492
{v : []byte (nil ), want : `null` },
479
493
{v : struct { M string }{"gopher" }, want : `{"M":"gopher"}` },
480
494
{v : struct { M Marshaler }{}, want : `{"M":null}` },
481
- {v : struct { M Marshaler }{(* nilMarshaler )(nil )}, want : `{"M":"0zenil0"}` },
482
- {v : struct { M interface {} }{(* nilMarshaler )(nil )}, want : `{"M":null}` },
495
+ {v : struct { M Marshaler }{(* nilJSONMarshaler )(nil )}, want : `{"M":"0zenil0"}` },
496
+ {v : struct { M interface {} }{(* nilJSONMarshaler )(nil )}, want : `{"M":null}` },
497
+ {v : struct { M encoding.TextMarshaler }{}, want : `{"M":null}` },
498
+ {v : struct { M encoding.TextMarshaler }{(* nilTextMarshaler )(nil )}, want : `{"M":"0zenil0"}` },
499
+ {v : struct { M interface {} }{(* nilTextMarshaler )(nil )}, want : `{"M":null}` },
483
500
}
484
501
485
502
for _ , tt := range testCases {
0 commit comments