Skip to content

Commit

Permalink
JSON "" shouldn't unmarshal to a null null.String.
Browse files Browse the repository at this point in the history
That's what the zero package is for.
This was a "feature", but inconsistent with the rest of the null package.
  • Loading branch information
guregu committed Oct 2, 2015
1 parent 4ac4f00 commit a9db3ac
Show file tree
Hide file tree
Showing 3 changed files with 8 additions and 6 deletions.
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
@@ -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)
`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

Expand All @@ -13,7 +13,7 @@ All types implement `sql.Scanner` and `driver.Valuer`, so you can use this libra

### null package

`import "gopkg.in/guregu/null.v2"`
`import "gopkg.in/guregu/null.v3"`

#### null.String
Nullable string.
Expand Down Expand Up @@ -41,7 +41,7 @@ Marshals to JSON null if SQL source data is null. Uses `time.Time`'s marshaler.

### zero package

`import "gopkg.in/guregu/null.v2/zero"`
`import "gopkg.in/guregu/null.v3/zero"`

#### zero.String
Nullable int64.
Expand Down
4 changes: 2 additions & 2 deletions string.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ func NewString(s string, valid bool) String {
}

// 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.
func (s *String) UnmarshalJSON(data []byte) error {
var err error
Expand All @@ -60,7 +60,7 @@ func (s *String) UnmarshalJSON(data []byte) error {
default:
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
}

Expand Down
4 changes: 3 additions & 1 deletion string_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,9 @@ func TestUnmarshalString(t *testing.T) {
var blank String
err = json.Unmarshal(blankStringJSON, &blank)
maybePanic(err)
assertNullStr(t, blank, "blank string json")
if !blank.Valid {
t.Error("blank string should be valid")
}

var null String
err = json.Unmarshal(nullJSON, &null)
Expand Down

0 comments on commit a9db3ac

Please sign in to comment.