golang 结构体转换到散列表map

func Struct2Map(obj interface{}) 
map[string]interface{} {
v := reflect.ValueOf(obj)
if v.Kind() == reflect.Ptr {

    v = v.Elem()
    obj = v.Interface()
    v = reflect.ValueOf(obj)
}
t := reflect.TypeOf(obj)
var data = make(map[string]interface{})
for i := 0; i < t.NumField(); i++ {
    data[t.Field(i).Name] = v.Field(i).Interface()
}
return data
}

共 0 个回复