UnmarshalJSON in null.Bool, null.Float, and null.String now return an error message when asked to unmarshal from an invalid type. This is in line with the behavior of the built-in sql library's null values.

This commit is contained in:
Joel Kek 2014-09-09 00:55:40 +08:00
parent 7cccb14361
commit f5cd2b14cc
3 changed files with 12 additions and 3 deletions

View file

@ -4,7 +4,8 @@ import (
"database/sql"
"encoding/json"
"errors"
// "fmt"
"fmt"
"reflect"
)
// Bool is an even nuller nullable bool.
@ -53,8 +54,8 @@ func (b *Bool) UnmarshalJSON(data []byte) error {
case nil:
b.Valid = false
return nil
// default:
// err = fmt.Errorf("json: cannot unmarshal %v into Go value of type null.Bool", v.(type).Name())
default:
err = fmt.Errorf("json: cannot unmarshal %v into Go value of type null.Bool", reflect.TypeOf(v).Name())
}
b.Valid = err == nil
return err

View file

@ -3,6 +3,8 @@ package null
import (
"database/sql"
"encoding/json"
"fmt"
"reflect"
"strconv"
)
@ -52,6 +54,8 @@ func (f *Float) UnmarshalJSON(data []byte) error {
case nil:
f.Valid = false
return nil
default:
err = fmt.Errorf("json: cannot unmarshal %v into Go value of type null.Float", reflect.TypeOf(v).Name())
}
f.Valid = err == nil
return err

View file

@ -6,6 +6,8 @@ package null
import (
"database/sql"
"encoding/json"
"fmt"
"reflect"
)
// String is an even nuller nullable string.
@ -51,6 +53,8 @@ func (s *String) UnmarshalJSON(data []byte) error {
case nil:
s.Valid = false
return nil
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 != "")
return err