-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjson.go
97 lines (75 loc) · 1.53 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package types
import (
"bytes"
"database/sql/driver"
"encoding/json"
"fmt"
)
type JSON[T any] struct {
V T
Valid bool
}
func NewJSON[T any](v T) JSON[T] {
return JSON[T]{V: v, Valid: true}
}
func (s *JSON[T]) Scan(value interface{}) error {
if value == nil {
s.V, s.Valid = *new(T), false
return nil
}
s.Valid = true
switch v := value.(type) {
case []byte:
// Parse the JSON data
decoder := json.NewDecoder(bytes.NewReader(v))
decoder.UseNumber()
if err := decoder.Decode(&s.V); err != nil {
return err
}
return nil
case string:
// Parse the JSON string
decoder := json.NewDecoder(bytes.NewReader([]byte(v)))
decoder.UseNumber()
if err := decoder.Decode(&s.V); err != nil {
return err
}
return nil
default:
return fmt.Errorf("%T, %w", value, ErrUnsupportedType)
}
}
func (s JSON[T]) Value() (driver.Value, error) {
if !s.Valid {
return nil, nil
}
// Convert the JSON to JSON
b, err := json.Marshal(s.V)
if err != nil {
return nil, err
}
if bytes.Equal(b, []byte("null")) {
return nil, nil
}
return b, nil
}
func (s JSON[T]) MarshalJSON() ([]byte, error) {
if !s.Valid {
return []byte("null"), nil
}
return json.Marshal(s.V)
}
func (s *JSON[T]) UnmarshalJSON(data []byte) error {
if data == nil || bytes.Equal(data, []byte("null")) {
s.V, s.Valid = *new(T), false
return nil
}
// Parse the JSON data
decoder := json.NewDecoder(bytes.NewReader(data))
decoder.UseNumber()
if err := decoder.Decode(&s.V); err != nil {
return err
}
s.Valid = true
return nil
}