JSON "" shouldn't unmarshal to a null null.String.

That's what the zero package is for.
This was a "feature", but inconsistent with the rest of the null package.
This commit is contained in:
Greg 2015-10-02 14:42:03 +09:00
parent 4ac4f00378
commit a9db3ac26f
3 changed files with 8 additions and 6 deletions

View file

@ -1,5 +1,5 @@
## null [![GoDoc](https://godoc.org/github.com/guregu/null?status.svg)](https://godoc.org/github.com/guregu/null) [![Coverage](http://gocover.io/_badge/github.com/guregu/null)](http://gocover.io/github.com/guregu/null) ## null [![GoDoc](https://godoc.org/github.com/guregu/null?status.svg)](https://godoc.org/github.com/guregu/null) [![Coverage](http://gocover.io/_badge/github.com/guregu/null)](http://gocover.io/github.com/guregu/null)
`import "gopkg.in/guregu/null.v2"` `import "gopkg.in/guregu/null.v3"`
null is a library with reasonable options for dealing with nullable SQL and JSON values null is a library with reasonable options for dealing with nullable SQL and JSON values
@ -13,7 +13,7 @@ All types implement `sql.Scanner` and `driver.Valuer`, so you can use this libra
### null package ### null package
`import "gopkg.in/guregu/null.v2"` `import "gopkg.in/guregu/null.v3"`
#### null.String #### null.String
Nullable string. Nullable string.
@ -41,7 +41,7 @@ Marshals to JSON null if SQL source data is null. Uses `time.Time`'s marshaler.
### zero package ### zero package
`import "gopkg.in/guregu/null.v2/zero"` `import "gopkg.in/guregu/null.v3/zero"`
#### zero.String #### zero.String
Nullable int64. Nullable int64.

View file

@ -41,7 +41,7 @@ func NewString(s string, valid bool) String {
} }
// UnmarshalJSON implements json.Unmarshaler. // UnmarshalJSON implements json.Unmarshaler.
// It supports string and null input. Blank string input produces a null String. // It supports string and null input. Blank string input does not produce a null String.
// It also supports unmarshalling a sql.NullString. // It also supports unmarshalling a sql.NullString.
func (s *String) UnmarshalJSON(data []byte) error { func (s *String) UnmarshalJSON(data []byte) error {
var err error var err error
@ -60,7 +60,7 @@ func (s *String) UnmarshalJSON(data []byte) error {
default: default:
err = fmt.Errorf("json: cannot unmarshal %v into Go value of type null.String", reflect.TypeOf(v).Name()) err = fmt.Errorf("json: cannot unmarshal %v into Go value of type null.String", reflect.TypeOf(v).Name())
} }
s.Valid = (err == nil) && (s.String != "") s.Valid = err == nil
return err return err
} }

View file

@ -52,7 +52,9 @@ func TestUnmarshalString(t *testing.T) {
var blank String var blank String
err = json.Unmarshal(blankStringJSON, &blank) err = json.Unmarshal(blankStringJSON, &blank)
maybePanic(err) maybePanic(err)
assertNullStr(t, blank, "blank string json") if !blank.Valid {
t.Error("blank string should be valid")
}
var null String var null String
err = json.Unmarshal(nullJSON, &null) err = json.Unmarshal(nullJSON, &null)