-
Notifications
You must be signed in to change notification settings - Fork 0
/
Deserializer.go
73 lines (61 loc) · 1.74 KB
/
Deserializer.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
package gosoon
import (
"reflect"
"strconv"
)
type deserializer struct {
provider ParsedJson
receiver interface{}
}
type fieldNameFunc func(string)
func Deserialize(json ParsedJson, toFill interface{}) {
deserializer{
provider: json,
receiver: toFill }.MapFields()
}
func (self deserializer) MapFields() {
self.eachFieldName(func(fieldName string) {
if !self.provider.AttributeIsNull(fieldName) {
fieldSetter{
field: self.receiverValue().FieldByName(fieldName),
value: self.provider.AttributeValue(fieldName) }.set()
}
})
}
func (self deserializer) receiverType() reflect.Type {
return reflect.TypeOf(self.receiver).Elem()
}
func (self deserializer) receiverValue() reflect.Value {
return reflect.ValueOf(self.receiver).Elem()
}
func (self deserializer) eachFieldName(fn fieldNameFunc) {
for i := 0; i < self.receiverType().NumField(); i += 1 {
fn(self.receiverType().Field(i).Name)
}
}
type fieldSetter struct {
value string
field reflect.Value
}
func (self fieldSetter) set() {
if self.field.CanSet() {
switch self.field.Kind() {
case reflect.Int:
self.field.SetInt(self.valueAsInt64())
case reflect.Float64, reflect.Float32:
self.field.SetFloat(self.valueAsFloat64())
case reflect.Bool:
self.field.SetBool(self.value == "true")
default:
self.field.SetString(self.value)
}
}
}
func (self fieldSetter) valueAsFloat64() float64 {
float, _ := strconv.ParseFloat(self.value, 64)
return float64(float)
}
func (self fieldSetter) valueAsInt64() int64 {
number, _ := strconv.Atoi(self.value)
return int64(number)
}