-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
int_slice.go
74 lines (54 loc) · 971 Bytes
/
int_slice.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
package unmarshal
import (
"strconv"
"strings"
"github.com/buger/jsonparser"
)
type IntSlice []int
func (i *IntSlice) UnmarshalJSON(b []byte) error {
var data, dataType, _, err = jsonparser.Get(b)
if err != nil {
return err
}
if len(data) == 0 {
*i = []int{}
return nil
}
str := string(data)
switch dataType {
case jsonparser.String:
split := strings.Split(str, ",")
var ints []int
for _, v := range split {
j, err := strconv.Atoi(v)
if err != nil {
return err
}
ints = append(ints, j)
}
*i = ints
return nil
case jsonparser.Number:
j, err := strconv.ParseInt(str, 10, 64)
if err != nil {
return err
}
*i = []int{int(j)}
return nil
case jsonparser.Boolean:
j, err := strconv.ParseBool(str)
if err != nil {
return err
}
if j {
*i = []int{1}
} else {
*i = []int{0}
}
return nil
case jsonparser.Null:
*i = []int{}
return nil
}
return newError(dataType, "[]int")
}