-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjson.go
More file actions
72 lines (54 loc) · 1.05 KB
/
json.go
File metadata and controls
72 lines (54 loc) · 1.05 KB
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
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
}
switch t := value.(type) {
case string:
nj.Json, nj.Valid = []byte(t), true
case []byte:
if len(t) == 0 {
nj.Json, nj.Valid = NullType, true
} else {
nj.Json, nj.Valid = t, true
}
default:
return errors.New("invalid type json")
}
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
}