github.com/TIBCOSoftware/flogo-lib@v0.5.9/core/mapper/exprmapper/json/util.go (about) 1 package json 2 3 import ( 4 "encoding/json" 5 "fmt" 6 "reflect" 7 ) 8 9 func ToArray(val interface{}) ([]interface{}, error) { 10 11 switch t := val.(type) { 12 case []interface{}: 13 return t, nil 14 15 case []map[string]interface{}: 16 var a []interface{} 17 for _, v := range t { 18 a = append(a, v) 19 } 20 return a, nil 21 case string: 22 a := make([]interface{}, 0) 23 if t != "" { 24 err := json.Unmarshal([]byte(t), &a) 25 if err != nil { 26 return nil, fmt.Errorf("unable to coerce %#v to map[string]interface{}", val) 27 } 28 } 29 return a, nil 30 case nil: 31 return nil, nil 32 default: 33 s := reflect.ValueOf(val) 34 if s.Kind() == reflect.Slice { 35 a := make([]interface{}, s.Len()) 36 37 for i := 0; i < s.Len(); i++ { 38 a[i] = s.Index(i).Interface() 39 } 40 return a, nil 41 } 42 return nil, fmt.Errorf("unable to coerce %#v to []interface{}", val) 43 } 44 } 45 46 func GetFieldByName(object interface{}, name string) (reflect.Value, error) { 47 val := reflect.ValueOf(object) 48 if val.Kind() == reflect.Ptr { 49 val = val.Elem() 50 } else { 51 } 52 53 field := val.FieldByName(name) 54 if field.IsValid() { 55 return field, nil 56 } 57 58 typ := reflect.TypeOf(object) 59 if typ.Kind() == reflect.Ptr { 60 typ = typ.Elem() 61 } 62 for i := 0; i < typ.NumField(); i++ { 63 p := typ.Field(i) 64 if !p.Anonymous { 65 if p.Tag != "" && len(p.Tag) > 0 { 66 if name == p.Tag.Get("json") { 67 return val.FieldByName(typ.Field(i).Name), nil 68 } 69 } 70 } 71 } 72 73 return reflect.Value{}, nil 74 } 75 76 func IsMapperableType(data interface{}) bool { 77 switch t := data.(type) { 78 case map[string]interface{}, map[string]string, []int, []int64, []string, []map[string]interface{}, []map[string]string: 79 return true 80 case []interface{}: 81 // 82 isStruct := true 83 for _, v := range t { 84 if v != nil { 85 if reflect.TypeOf(v).Kind() == reflect.Struct { 86 isStruct = false 87 break 88 } else if reflect.TypeOf(v).Kind() == reflect.Ptr { 89 isStruct = false 90 break 91 } 92 } 93 } 94 return isStruct 95 } 96 97 return false 98 }