go中Struct转map,map转Struct的测试

package main

import (
	"fmt"
	"github.com/mitchellh/mapstructure"
	"reflect"
	"time"
)

func main() {
	type Info struct {
		Addr string `json:"addr" mapstructure:"addr"`
	}
	type User struct {
		UserName string    `json:"user_name" mapstructure:"user_name"`
		Info     Info      `json:"info" mapstructure:"info"`
		Time     time.Time `json:"time" mapstructure:"time"`
	}
	user := User{
		UserName: "u1",
		Info: Info{
			Addr: "a1",
		},
		Time: time.Now(),
	}

	// 测试使用 mapstructure 库将 Struct 转为 map,时间的转换会有问题
	var msUserMap map[string]interface{}
	_ = mapstructure.Decode(user, &msUserMap)
	fmt.Printf("%#v\n", msUserMap)

	// 测试使用反射将 Struct 转为 map,但只是单层,Info仍然是结构体
	userMap := StructToMap(user)
	fmt.Printf("%#v\n", userMap)

	// 将 map 转为 Struct
	var u1 User
	_ = mapstructure.Decode(userMap, &u1)
	fmt.Printf("%#v\n", u1)
}

func StructToMap(obj interface{}) map[string]interface{} {
	obj1 := reflect.TypeOf(obj)
	obj2 := reflect.ValueOf(obj)

	data := make(map[string]interface{})
	for i := 0; i < obj1.NumField(); i++ {
		if obj1.Field(i).Tag.Get("mapstructure") != "" {
			data[obj1.Field(i).Tag.Get("mapstructure")] = obj2.Field(i).Interface()
		} else {
			data[obj1.Field(i).Name] = obj2.Field(i).Interface()
		}
	}
	return data
}