From e2ba99c511dbf4fe76b23156c4525e67d07acc4d Mon Sep 17 00:00:00 2001 From: Matthew Dillon Date: Tue, 2 Jun 2015 12:26:46 -0800 Subject: [PATCH] Add NullBool type --- types.go | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/types.go b/types.go index ca16199..80f5259 100644 --- a/types.go +++ b/types.go @@ -12,6 +12,36 @@ import ( "github.com/lib/pq" ) +type NullBool struct { + sql.NullBool +} + +func (b *NullBool) MarshalJSON() ([]byte, error) { + if !b.Valid { + return []byte("null"), nil + } + return json.Marshal(b.Bool) +} + +func (n *NullBool) UnmarshalJSON(b []byte) error { + if bytes.Equal(b, []byte("null")) { + n.Bool = false + n.Valid = false + return nil + } + var x interface{} + var err error + json.Unmarshal(b, &x) + switch x.(type) { + case bool: + err = json.Unmarshal(b, &n.Bool) + case map[string]interface{}: + err = json.Unmarshal(b, &n.NullBool) + } + n.Valid = true + return err +} + type NullString struct { sql.NullString }