人生列车

follow on!success!

导航

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

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
}

 

posted on 2018-05-22 22:03  tianxia2s  阅读(1308)  评论(0编辑  收藏  举报