我的Github仓库github.com/liangyaopei/struct_to_map 假设有下面的一个结构体 funcnewUser()User{name:="user"MyGithub:=GithubPage{URL:"https://github.com/liangyaopei",Star:1,}NoDive:=StructNoDive{NoDive:1}dateStr:="2020-07-21 12:00:00"date,_:=time.Parse(timeLayout,dateStr)profile:=...
func structToMap(s interface{}) map[string]interface{} { result := make(map[string]interface{}) // 使用反射获取结构体字段信息 v := reflect.ValueOf(s) t := reflect.TypeOf(s) for i := 0; i < t.NumField(); i++ { // 将结构体字段名和值存储到Map中 result[t.Field(i).Name] ...
funcReflectMethod(objinterface{})map[string]interface{} { t := reflect.TypeOf(obj) v := reflect.ValueOf(obj)vardata =make(map[string]interface{})fori :=0; i < t.NumField(); i++ { data[strings.ToLower(t.Field(i).Name)] = v.Field(i).Interface() }returndata } 使用第三方库 ...
// 方法1:使用go中标准库里的json编码成[]byte,然后再解码到map里 //data, _ := json.Marshal(&User)//m := make(map[string]any) //json.Unmarshal(data, &m)//Struct2map方法2:通过反射将struct转换成mapfuncStruct2map(obj any) (datamap[string]any, err error) { ...
(map[string]interface{})objT:=reflect.TypeOf(elem)objV:=reflect.ValueOf(elem)fori:=0;i<objT.NumField();i++{data[objT.Field(i).Name]=objV.Field(i).Interface()}res=append(res,data)}fmt.Printf("=== Convert Result ===\n%+v\n",res)}funcmain(){varpeople[]interface{}// 切片...
1.map 转 struct map转struct有两种方式 1.是通过第三方包github.com/mitchellh/mapstructure 2.通过map转json,再通过json转struct 第三方包 mapstructure 下载依赖,通过第三方依赖进行转换 go gethttp://github.com/goinggo/mapstructure func TestMapToStructByMod(t *testing.T) { ...
StructToJsonDemo() } AI代码助手复制代码 输出: 二、json和map互转 (1)json转map例子: funcJsonToMapDemo(){ jsonStr :=` { "name": "jqw", "age": 18 } `varmapResultmap[string]interface{} err := json.Unmarshal([]byte(jsonStr), &mapResult)iferr !=nil{ ...
Convert struct to a map Extract the fields of a struct to a []string Extract the values of a struct to a []values Check if a struct is initialized or not Check if a passed interface is a struct or a pointer to struct You can see some examples here: http://godoc.org/github.com/...
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) ...