-
Notifications
You must be signed in to change notification settings - Fork 0
/
jsonproperty.go
68 lines (58 loc) · 1.67 KB
/
jsonproperty.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
package jsonproperty
import (
"appengine/datastore"
"encoding/json"
"reflect"
)
type JsonProperty map[string]interface{}
// entity must be a pointer to a struct
func LoadJsonProperties(entity interface{}, c <-chan datastore.Property) (<-chan datastore.Property, error) {
jsonProperties := map[string]reflect.Value{} // {name: value}
// Builds jsonProperties
value := reflect.ValueOf(entity).Elem()
for i := 0; i < value.NumField(); i++ {
value2 := value.Field(i)
if value2.Type() == jsonPropertyType {
jsonProperties[nameFromField(value.Type().Field(i))] = value2
}
}
// Builds return channel
c2 := make(chan datastore.Property, value.NumField()-len(jsonProperties))
defer close(c2)
for property := range c {
if jsonValue, ok := jsonProperties[property.Name]; ok {
bytes := []byte(property.Value.(string))
if err := json.Unmarshal(bytes, jsonValue.Addr().Interface()); err != nil {
return c2, err
}
} else {
c2 <- property
}
}
return c2, nil
}
// entity must be a pointer to a struct
func SaveJsonProperties(entity interface{}, c chan<- datastore.Property) (chan<- datastore.Property, error) {
value := reflect.ValueOf(entity).Elem()
for i := 0; i < value.NumField(); i++ {
value2 := value.Field(i)
if value2.Type() == jsonPropertyType {
bytes, err := json.Marshal(value2.Interface())
if err != nil {
return c, err
}
c <- datastore.Property{
Name: nameFromField(value.Type().Field(i)),
Value: string(bytes),
}
}
}
return c, nil
}
var jsonPropertyType = reflect.TypeOf(JsonProperty{})
func nameFromField(f reflect.StructField) string {
if name := f.Tag.Get("jsonproperty"); name != "" {
return name
}
return f.Name
}