golang struct转map 文心快码BaiduComate 在Go语言中,将结构体(struct)转换为map(特别是从map[string]interface{}类型)通常需要使用反射(reflection)机制,因为Go是静态类型语言,而结构体和map在内存中的表示和访问方式有所不同。下面,我将根据您的提示,逐步说明如何实现这一转换,并提供相应的代码示例。 1. 创建一...
直接使用json.Marshal方法来强制转化struct。 参考代码: funcJSONMethod(contentinterface{})map[string]interface{} {varnamemap[string]interface{}ifmarshalContent, err := json.Marshal(content); err !=nil{ fmt.Println(err) }else{ d := json.NewDecoder(bytes.NewReader(marshalContent)) d.UseNumber()...
mapInstance := make(map[string]interface{}) mapInstance["Name"] ="jqw"mapInstance["Age"] =18varpeople People err := mapstructure.Decode(mapInstance, &people)iferr !=nil { fmt.Println(err) } fmt.Println(people) } struct转map例子 func StructToMapDemo(objinterface{}) map[string]interface{...
先将map转换成JSON,再通过 JSON 转换成struct 操作有点繁琐 func TestMapToStructByJson(t *testing.T) { beforeMap := map[string]interface {}{ "id":"123", "user_name":"酒窝猪", "address":[]map[string]interface{}{{"address": "address01"}, {"address": "address02"}}, } var afterSt...
type Person struct { Name string Age int Gender string } ``` ### 步骤 2:创建一个函数,将结构体转换为Map 接下来,我们创建一个将结构体转换为Map的函数: ```go func structToMap(s interface{}) map[string]interface{} { result := make(map[string]interface{}) /...
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() ...
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{})...
golangstruct转map golangstruct转map struct转map 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)...
beforeMap := map[string]interface {}{ "id":"123", "user_name":"酒窝猪", "address":[]map[string]interface{}{{"address": "address01"}, {"address": "address02"}}, } var afterStruct =UserInfoVo{} before := time.Now() marshal, err := json.Marshal(beforeMap) if err!=nil{ fmt...
func Struct2Map(obj interface{}) map[string]interface{} { t := reflect.TypeOf(obj) v := reflect.ValueOf(obj) var data = make(map[string]interface{}) fori := 0; i < t.NumField(); i++ { data[t.Field(i).Name] = v.Field(i).Interface() ...