Go语言高级特性总结——Struct、Map与JSON之间的转化

Struct与Map之间互相转换

 // Struct2Map convert struct to map
func Struct2Map(st interface{}) map[string]interface{} {
vt := reflect.TypeOf(st)
vv := reflect.ValueOf(st)
var data = make(map[string]interface{})
for i := ; i < vt.NumField(); i++ {
f := vt.Field(i)
v := vv.Field(i)
chKey := f.Tag.Get("json")
switch v.Kind() {
case reflect.String:
if s, ok := v.Interface().(string); ok && s != "" {
data[chKey] = s
}
case reflect.Int:
if i, ok := v.Interface().(int); ok && i != {
data[chKey] = i
}
case reflect.Struct:
if t, ok := v.Interface().(time.Time); ok && t != (time.Time{}) {
data[chKey] = t
}
case reflect.Uint64:
if u64, ok := v.Interface().(uint64); ok && u64 != {
data[chKey] = u64
}
case reflect.Uint:
if u, ok := v.Interface().(uint); ok && u != {
data[chKey] = u
}
default:
log.Error("unsupport common query type: " + string(chKey))
}
}
return data
}

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
}
上一篇:golang struct


下一篇:记一次坑爹的golang 二维map判断问题