Go struct 转 map(利用反射reflect)

package main

import (
    "fmt"
    "reflect"
)

type User struct {
    Id       int    `json:"id"`
    Username string `json:"username"`
    Password string `json:"password"`
}

func Struct2Map(obj interface{}) map[string]interface{} {
    t := reflect.TypeOf(obj)
    v := reflect.ValueOf(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
}

func main() {
    user := User{5, "zhangsan", "password"}
    data := Struct2Map(user)
    fmt.Printf("struct2map得到的map内容为:%v \n", data)
}

你可能感兴趣的:(Go struct 转 map(利用反射reflect))