標籤:fun class field 轉化 erro key inter ring turn
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] = s14 }15 case reflect.Int:16 if i, ok := v.Interface().(int); ok && i != 0 {17 data[chKey] = i18 }19 case reflect.Struct:20 if t, ok := v.Interface().(time.Time); ok && t != (time.Time{}) {21 data[chKey] = t22 }23 case reflect.Uint64:24 if u64, ok := v.Interface().(uint64); ok && u64 != 0 {25 data[chKey] = u6426 }27 case reflect.Uint:28 if u, ok := v.Interface().(uint); ok && u != 0 {29 data[chKey] = u30 }31 default:32 log.Error("unsupport common query type: " + string(chKey))33 }34 }35 return data36 }
JSON與Map之間的轉換
// JSONString2Map convert struct to mapfunc 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 jsonfunc Map2JSON(jsonmap map[string]string) (string, error) { jbytes, err := json.Marshal(jsonmap) return string(jbytes), err}
Go語言進階特性總結——Struct、Map與JSON之間的轉化