-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdeserialize.go
97 lines (79 loc) · 2.16 KB
/
deserialize.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 serializer
import (
"encoding/csv"
"encoding/json"
"encoding/xml"
"fmt"
"reflect"
"strings"
)
func (s *Serializer) Deserialize(data string, obj any) error {
if !isPointer(obj) {
return fmt.Errorf("object must be pointer")
}
switch s.Format {
case JSON:
return json.Unmarshal([]byte(data), obj)
case XML:
return xml.Unmarshal([]byte(data), obj)
case CSV:
return s.deserializeCSV(data, obj)
default:
return fmt.Errorf("Unsupported format: %s", s.Format)
}
}
func (s *Serializer) MergeObjects(target interface{}, source interface{}) error {
targetValue := reflect.ValueOf(target)
sourceValue := reflect.ValueOf(source)
if targetValue.Kind() != reflect.Ptr || sourceValue.Kind() != reflect.Ptr {
return fmt.Errorf("both target and source must be pointers")
}
targetValue = targetValue.Elem()
sourceValue = sourceValue.Elem()
for i := 0; i < targetValue.NumField(); i++ {
targetField := targetValue.Field(i)
sourceField := sourceValue.Field(i)
if targetField.CanSet() && !isEmpty(sourceField) {
targetField.Set(sourceField)
}
}
return nil
}
func (s *Serializer) DeserializeAndMerge(data string, target interface{}) error {
source := reflect.New(reflect.TypeOf(target).Elem()).Interface()
if err := s.Deserialize(data, source); err != nil {
return err
}
return s.MergeObjects(target, source)
}
func isEmpty(v reflect.Value) bool {
zero := reflect.Zero(v.Type())
return reflect.DeepEqual(v.Interface(), zero.Interface())
}
func isPointer(v interface{}) bool {
t := reflect.TypeOf(v)
return t.Kind() == reflect.Ptr
}
func (s *Serializer) deserializeCSV(data string, obj any) error {
value := reflect.ValueOf(obj)
if value.Kind() != reflect.Ptr || value.IsNil() {
return fmt.Errorf("Invalid object type for CSV deserialization")
}
reader := csv.NewReader(strings.NewReader(data))
rows, err := reader.ReadAll()
if err != nil {
return err
}
elemType := value.Elem().Type()
elem := reflect.New(elemType).Elem()
for _, row := range rows {
for i, fieldValue := range row {
field := elem.Field(i)
if field.IsValid() && field.CanSet() {
field.SetString(fieldValue)
}
}
}
value.Elem().Set(elem)
return nil
}