diff --git a/string.go b/string.go index 503e6f2..554aac8 100644 --- a/string.go +++ b/string.go @@ -73,6 +73,15 @@ func (s String) MarshalJSON() ([]byte, error) { return json.Marshal(s.String) } +// MarshalText implements encoding.TextMarshaler. +// It will encode a blank string when this String is null. +func (s String) MarshalText() ([]byte, error) { + if !s.Valid { + return []byte{}, nil + } + return []byte(s.String), nil +} + // UnmarshalText implements encoding.TextUnmarshaler. // It will unmarshal to a null String if the input is a blank string. func (s *String) UnmarshalText(text []byte) error { diff --git a/string_test.go b/string_test.go index 38f80bb..c02d6b0 100644 --- a/string_test.go +++ b/string_test.go @@ -93,17 +93,26 @@ func TestMarshalString(t *testing.T) { data, err := json.Marshal(str) maybePanic(err) assertJSONEquals(t, data, `"test"`, "non-empty json marshal") + data, err = str.MarshalText() + maybePanic(err) + assertJSONEquals(t, data, "test", "non-empty text marshal") // empty values should be encoded as an empty string zero := StringFrom("") data, err = json.Marshal(zero) maybePanic(err) assertJSONEquals(t, data, `""`, "empty json marshal") + data, err = zero.MarshalText() + maybePanic(err) + assertJSONEquals(t, data, "", "string marshal text") null := StringFromPtr(nil) data, err = json.Marshal(null) maybePanic(err) assertJSONEquals(t, data, `null`, "null json marshal") + data, err = null.MarshalText() + maybePanic(err) + assertJSONEquals(t, data, "", "string marshal text") } // Tests omitempty... broken until Go 1.4