-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjsonutil.go
111 lines (106 loc) · 2.48 KB
/
jsonutil.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package jobrunner
import (
"bytes"
"encoding/json"
"fmt"
"reflect"
"strconv"
"strings"
)
var (
typeOfString = reflect.TypeOf((*string)(nil))
typeOfBool = reflect.TypeOf((*bool)(nil))
typeOfInteger = reflect.TypeOf((*int)(nil))
typeOfInt64 = reflect.TypeOf((*int64)(nil))
typeOfFloat64 = reflect.TypeOf((*float64)(nil))
typeOfByte = reflect.TypeOf((*byte)(nil))
)
// marshalIgnoreError returns the string representation of the given object; returns empty string in case of error
func marshalIgnoreError(v interface{}) string {
var buffer = &bytes.Buffer{}
var encoder = json.NewEncoder(buffer)
encoder.SetEscapeHTML(false)
encoder.Encode(v)
var result = buffer.String()
return strings.TrimRight(result, "\n")
}
func tryUnmarshalPrimitiveTypes(value string, dataTemplate interface{}) bool {
if value == "" {
return true
}
switch reflect.TypeOf(dataTemplate) {
case typeOfString:
(*(dataTemplate).(*string)) = value
return true
case typeOfBool:
var parsedValue, parseError = strconv.ParseBool(
strings.ToLower(
value,
),
)
if parseError != nil {
return false
}
(*(dataTemplate).(*bool)) = parsedValue
return true
case typeOfInteger:
var parsedValue, parseError = strconv.Atoi(value)
if parseError != nil {
return false
}
(*(dataTemplate).(*int)) = parsedValue
return true
case typeOfInt64:
var parsedValue, parseError = strconv.ParseInt(value, 0, 64)
if parseError != nil {
return false
}
(*(dataTemplate).(*int64)) = parsedValue
return true
case typeOfFloat64:
var parsedValue, parseError = strconv.ParseFloat(value, 64)
if parseError != nil {
return false
}
(*(dataTemplate).(*float64)) = parsedValue
return true
case typeOfByte:
var parsedValue, parseError = strconv.ParseUint(value, 0, 8)
if parseError != nil {
return false
}
(*(dataTemplate).(*byte)) = byte(parsedValue)
return true
}
return false
}
// tryUnmarshal tries to unmarshal given value to dataTemplate
func tryUnmarshal(value string, dataTemplate interface{}) error {
if isInterfaceValueNil(dataTemplate) {
return nil
}
if tryUnmarshalPrimitiveTypes(
value,
dataTemplate,
) {
return nil
}
var noQuoteJSONError = json.Unmarshal(
[]byte(value),
dataTemplate,
)
if noQuoteJSONError == nil {
return nil
}
var withQuoteJSONError = json.Unmarshal(
[]byte("\""+value+"\""),
dataTemplate,
)
if withQuoteJSONError == nil {
return nil
}
return fmt.Errorf(
"Unable to unmarshal value [%v] into data template",
value,
)
}