We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent aa8aa51 commit 41961ceCopy full SHA for 41961ce
string.go
@@ -73,6 +73,15 @@ func (s String) MarshalJSON() ([]byte, error) {
73
return json.Marshal(s.String)
74
}
75
76
+// MarshalText implements encoding.TextMarshaler.
77
+// It will encode a blank string when this String is null.
78
+func (s String) MarshalText() ([]byte, error) {
79
+ if !s.Valid {
80
+ return []byte{}, nil
81
+ }
82
+ return []byte(s.String), nil
83
+}
84
+
85
// UnmarshalText implements encoding.TextUnmarshaler.
86
// It will unmarshal to a null String if the input is a blank string.
87
func (s *String) UnmarshalText(text []byte) error {
string_test.go
@@ -93,17 +93,26 @@ func TestMarshalString(t *testing.T) {
93
data, err := json.Marshal(str)
94
maybePanic(err)
95
assertJSONEquals(t, data, `"test"`, "non-empty json marshal")
96
+ data, err = str.MarshalText()
97
+ maybePanic(err)
98
+ assertJSONEquals(t, data, "test", "non-empty text marshal")
99
100
// empty values should be encoded as an empty string
101
zero := StringFrom("")
102
data, err = json.Marshal(zero)
103
104
assertJSONEquals(t, data, `""`, "empty json marshal")
105
+ data, err = zero.MarshalText()
106
107
+ assertJSONEquals(t, data, "", "string marshal text")
108
109
null := StringFromPtr(nil)
110
data, err = json.Marshal(null)
111
112
assertJSONEquals(t, data, `null`, "null json marshal")
113
+ data, err = null.MarshalText()
114
115
116
117
118
// Tests omitempty... broken until Go 1.4
0 commit comments