1. 程式人生 > >Go語言高級特性總結——Struct、Map與JSON之間的轉化

Go語言高級特性總結——Struct、Map與JSON之間的轉化

err bsp make 特性 clas 高級 string comm tag

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
}

Go語言高級特性總結——Struct、Map與JSON之間的轉化