MarshalText for null.String
forgot to add this
This commit is contained in:
parent
aa8aa51503
commit
41961cea03
2 changed files with 18 additions and 0 deletions
|
@ -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 {
|
||||
|
|
|
@ -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
|
||||
|
|
Loading…
Reference in a new issue