-
Notifications
You must be signed in to change notification settings - Fork 0
/
jsonb.go
46 lines (39 loc) · 952 Bytes
/
jsonb.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package pg
import (
"encoding/json"
"errors"
"github.com/guregu/null"
)
type JSONB null.String
func (j *JSONB) Encode(src interface{}) error {
jsonData, err := json.Marshal(src)
if err != nil {
return err
}
*j = JSONB(null.NewString(string(jsonData), true))
return nil
}
func (j *JSONB) Decode(dst interface{}) error {
if !j.NullString.Valid {
return errors.New("Empty JSON data")
}
return json.Unmarshal([]byte(j.NullString.String), dst)
}
// MarshalJSON implements the `json.Marshaller` interface
func (j *JSONB) MarshalJSON() ([]byte, error) {
if j.NullString.Valid {
return []byte(j.NullString.String), nil
}
return []byte("null"), nil
}
// UnmarshalJSON implements the `json.Unmarshaler` interface
func (j *JSONB) UnmarshalJSON(bytes []byte) error {
if len(bytes) > 0 {
j.NullString.String = string(bytes)
j.NullString.Valid = true
} else {
j.NullString.String = ""
j.NullString.Valid = false
}
return nil
}