-
Notifications
You must be signed in to change notification settings - Fork 0
/
json.go
78 lines (56 loc) · 1.06 KB
/
json.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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package nullish
import (
"bytes"
"database/sql/driver"
"errors"
"github.com/goccy/go-json"
)
type NullJSON struct {
Json json.RawMessage
Valid bool
}
// Value method
func (nj NullJSON) Value() (driver.Value, error) {
if !nj.Valid {
return nil, nil
}
return json.Marshal(nj.Json)
}
// Scan method
func (nj *NullJSON) Scan(value interface{}) error {
if value == nil {
nj.Json, nj.Valid = json.RawMessage{}, false
return nil
}
var res []byte
switch t := value.(type) {
case string:
res = []byte(t)
case []byte:
if len(t) == 0 {
res = NullType
} else {
res = []byte(string(t))
}
default:
return errors.New("invalid type json")
}
nj.Json, nj.Valid = res, true
return nil
}
// MarshalJSON method
func (nj NullJSON) MarshalJSON() ([]byte, error) {
if !nj.Valid {
return NullType, nil
}
return json.Marshal(nj.Json)
}
// UnmarshalJSON method
func (nj *NullJSON) UnmarshalJSON(data []byte) error {
if bytes.Equal(data, NullType) {
*nj = NullJSON{}
return nil
}
*nj = NullJSON{Json: data, Valid: true}
return nil
}