Skip to content

Commit

Permalink
entity_unmarshal: Check if type is struct before calling NumField()
Browse files Browse the repository at this point in the history
  • Loading branch information
xzou committed Mar 28, 2019
1 parent 68b5b34 commit 509e2ae
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 21 deletions.
4 changes: 4 additions & 0 deletions entity_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -413,6 +413,10 @@ var sampleEntityJSON = `{
"latitude": 38.9243983751914,
"longitude": -77.2178385786886
},
"googleAttributes": {
"wi_fi": ["free_wi_fi"],
"welcomes_dogs": ["true"]
},
"meta": {
"accountId": "3549951188342570541",
"uid": "b3JxON",
Expand Down
44 changes: 23 additions & 21 deletions entity_unmarshal.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,32 +7,34 @@ import (
)

func unmarshal(i interface{}, m map[string]interface{}) interface{} {
var jsonTagToKey = map[string]string{}
val := Indirect(reflect.ValueOf(i))
for i := 0; i < val.Type().NumField(); i++ {
field := val.Type().Field(i)
tag := strings.Replace(field.Tag.Get("json"), ",omitempty", "", -1)
jsonTagToKey[tag] = field.Name
}
if val.Kind() == reflect.Struct {
var jsonTagToKey = map[string]string{}
for i := 0; i < val.Type().NumField(); i++ {
field := val.Type().Field(i)
tag := strings.Replace(field.Tag.Get("json"), ",omitempty", "", -1)
jsonTagToKey[tag] = field.Name
}

for tag, val := range m {
if _, ok := jsonTagToKey[tag]; ok {
if val == nil {
v := Indirect(reflect.ValueOf(i)).FieldByName(jsonTagToKey[tag])
for tag, val := range m {
if _, ok := jsonTagToKey[tag]; ok {
if val == nil {
v := Indirect(reflect.ValueOf(i)).FieldByName(jsonTagToKey[tag])

// Check if double pointer
if v.Type().Kind() == reflect.Ptr {
t := v.Type()
for t.Kind() == reflect.Ptr && t.Elem().Kind() == reflect.Ptr {
t = t.Elem()
// Check if double pointer
if v.Type().Kind() == reflect.Ptr {
t := v.Type()
for t.Kind() == reflect.Ptr && t.Elem().Kind() == reflect.Ptr {
t = t.Elem()
}
typedNil := reflect.New(t)
Indirect(reflect.ValueOf(i)).FieldByName(jsonTagToKey[tag]).Set(reflect.ValueOf(typedNil.Interface()))
}
typedNil := reflect.New(t)
Indirect(reflect.ValueOf(i)).FieldByName(jsonTagToKey[tag]).Set(reflect.ValueOf(typedNil.Interface()))
} else if vMap, ok := val.(map[string]interface{}); ok {
v := Indirect(reflect.ValueOf(i)).FieldByName(jsonTagToKey[tag])
r := unmarshal(v.Interface(), vMap)
Indirect(reflect.ValueOf(i)).FieldByName(jsonTagToKey[tag]).Set(reflect.ValueOf(r))
}
} else if vMap, ok := val.(map[string]interface{}); ok {
v := Indirect(reflect.ValueOf(i)).FieldByName(jsonTagToKey[tag])
r := unmarshal(v.Interface(), vMap)
Indirect(reflect.ValueOf(i)).FieldByName(jsonTagToKey[tag]).Set(reflect.ValueOf(r))
}
}
}
Expand Down

0 comments on commit 509e2ae

Please sign in to comment.