在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
Struct与Map之间互相转换 1 // Struct2Map convert struct to map 2 func Struct2Map(st interface{}) map[string]interface{} { 3 vt := reflect.TypeOf(st) 4 vv := reflect.ValueOf(st) 5 var data = make(map[string]interface{}) 6 for i := 0; i < vt.NumField(); i++ { 7 f := vt.Field(i) 8 v := vv.Field(i) 9 chKey := f.Tag.Get("json") 10 switch v.Kind() { 11 case reflect.String: 12 if s, ok := v.Interface().(string); ok && s != "" { 13 data[chKey] = s 14 } 15 case reflect.Int: 16 if i, ok := v.Interface().(int); ok && i != 0 { 17 data[chKey] = i 18 } 19 case reflect.Struct: 20 if t, ok := v.Interface().(time.Time); ok && t != (time.Time{}) { 21 data[chKey] = t 22 } 23 case reflect.Uint64: 24 if u64, ok := v.Interface().(uint64); ok && u64 != 0 { 25 data[chKey] = u64 26 } 27 case reflect.Uint: 28 if u, ok := v.Interface().(uint); ok && u != 0 { 29 data[chKey] = u 30 } 31 default: 32 log.Error("unsupport common query type: " + string(chKey)) 33 } 34 } 35 return data 36 } JSON与Map之间的转换 // JSONString2Map convert struct to map func JSONString2Map(str string) (map[string]string, error) { result := make(map[string]string) err := json.Unmarshal([]byte(str), &result) return result, err } Map与JSON之间的转换 // Map2JSON conver map to json func Map2JSON(jsonmap map[string]string) (string, error) { jbytes, err := json.Marshal(jsonmap) return string(jbytes), err }
|
请发表评论