golang struct 转 map

package main

import (
    "fmt"
    "reflect"

    "github.com/mitchellh/mapstructure"
)

type User struct {
    Name    string `json:"name"`
    IsAdmin bool   `json:"is_admin"`
}

func MapToStruct() {
    mapInstance := make(map[string]interface{})
    mapInstance["Name"] = "Nick"
    mapInstance["IsAdmin"] = true

    var user User
    if err := mapstructure.Decode(mapInstance, &user); err != nil {
        fmt.Println(err)
    }
    fmt.Println("struct:", user)
}

func StructToMap(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() {

    MapToStruct()
    user := User{"Nick", true}
    userMap := StructToMap(user)
    fmt.Println("userMap:", userMap)

}
打赏作者

您将是第一位评论人!

提醒
avatar