资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

golang结构体转map

package main

import (
    "encoding/json"
    "fmt"
    "reflect"
    "time"
)

type Body struct {
    Person1 string
    Age     int
    Salary  float32
}

func Struct2Map(obj interface{}) (data map[string]interface{}, err error) {
    data = make(map[string]interface{})
    objT := reflect.TypeOf(obj)
    objV := reflect.ValueOf(obj)
    for i := 0; i < objT.NumField(); i++ {
        data[objT.Field(i).Name] = objV.Field(i).Interface()
    }
    err = nil
    return
}

func Test1() {
    t := time.Now()
    a := Body{"aaa", 2, 12.34}
    elem := reflect.ValueOf(&a).Elem()
    type_ := elem.Type()
    m := map[string]interface{}{}
    for i := 0; i < type_.NumField(); i++ {
        m[type_.Field(i).Name] = elem.Field(i).Interface()
    }
    fmt.Println(time.Now().Sub(t), m)
}

func Test2() {
    t := time.Now()
    persion := Body{"aaa", 2, 12.34}
    j, _ := json.Marshal(persion)
    fmt.Println(time.Now().Sub(t), string(j))
}

func Test3() {
    m := make(map[string]interface{})
    t := time.Now()
    persion := Body{"aaa", 2, 12.34}
    j, _ := json.Marshal(persion)
    json.Unmarshal(j, &m)
    fmt.Println(time.Now().Sub(t), m)
}

func Test4() {
    t := time.Now()
    persion := Body{"aaa", 2, 12.34}
    ret, _ := Struct2Map(persion)
    fmt.Println(time.Now().Sub(t), ret)
}

func main() {
    Test1()
    Test2()
    Test3()
    Test4()
}
package main

import (
    "fmt"
    "reflect"
    "time"
)

type User struct {
    Id        int64
    Username  string
    Password  string
    Logintime time.Time
}

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", "pwd", time.Now()}
    data := Struct2Map(user)
    fmt.Println(data)
}

名称栏目:golang结构体转map
当前地址:http://www.cdkjz.cn/article/gsphes.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

大客户专线   成都:13518219792   座机:028-86922220