package services import ( pkg "goiot-pkg/models" "reflect" ) // 把结构体转换为Int func InterfaceToInt(data interface{}) int { if p, ok := data.(float64); ok { return int(p) } return 0 } // 把结构体转换为Bool func InterfaceToBool(data interface{}) bool { if p, ok := data.(bool); ok { return p } return false } // 把结构体转换为Float32 func InterfaceToFloat32(data interface{}) float32 { if p, ok := data.(float64); ok { return float32(p) } return 0. } // 把结构体转换为IntDic func InterfaceToIntDic(data interface{}) pkg.IntDic { value := reflect.ValueOf(data) if value.Kind() != reflect.Slice { return nil } var intDic = make(pkg.IntDic, 0) for i := 0; i < value.Len(); i++ { em := reflect.ValueOf(data).Index(i).Elem() if em.Kind() != reflect.Map { continue } intP := pkg.IntP{} for _, key := range em.MapKeys() { if p, ok := em.MapIndex(key).Interface().(string); ok { intP.Key = p } else if p, ok := em.MapIndex(key).Interface().(float64); ok { intP.Value = int(p) } } intDic = append(intDic, intP) } return intDic } // 把结构体转换为BoolDic func InterfaceToBoolDic(data interface{}) pkg.BoolDic { value := reflect.ValueOf(data) if value.Kind() != reflect.Slice { return nil } var boolDic = make(pkg.BoolDic, 0) for i := 0; i < value.Len(); i++ { em := reflect.ValueOf(data).Index(i).Elem() if em.Kind() != reflect.Map { continue } boolP := pkg.BoolP{} for _, key := range em.MapKeys() { if p, ok := em.MapIndex(key).Interface().(string); ok { boolP.Key = p } else if p, ok := em.MapIndex(key).Interface().(bool); ok { boolP.Value = p } } boolDic = append(boolDic, boolP) } return boolDic } // 把结构体转换为StringDic func InterfaceToStringDic(data interface{}) pkg.StringDic { value := reflect.ValueOf(data) if value.Kind() != reflect.Slice { return nil } var stringDic = make(pkg.StringDic, 0) for i := 0; i < value.Len(); i++ { em := reflect.ValueOf(data).Index(i).Elem() if em.Kind() != reflect.Map { continue } stringP := pkg.StringP{} for _, key := range em.MapKeys() { if p, ok := em.MapIndex(key).Interface().(string); ok { stringP.Key = p } else if p, ok := em.MapIndex(key).Interface().(string); ok { stringP.Value = p } } stringDic = append(stringDic, stringP) } return stringDic }