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 } 使用第三方库 ...
//结构体转map方法2func StructToMapViaJson(data S)map[string]interface{} { m := make(map[string]interface{}) //struct 转json j, _ := json.Marshal(data) //json 转mapjson.Unmarshal(j, &m)returnm } func FillStruct(datamap[string]interface{}, obj interface{}) error {fork, v :=ran...
其中包含struct的域的展开,定制化struct的方法。 map[string]interface{}{"name":"user","no_dive":StructNoDive{NoDive:1},// dive struct field"url":"https://github.com/liangyaopei","star":1,// customized method"time":"2020-07-21 12:00:00",} 实现思路 & 源码解析 1.标签识别。 使用read...
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{}) /...
(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{}// 切片...
StructToJsonDemo() } AI代码助手复制代码 输出: 二、json和map互转 (1)json转map例子: funcJsonToMapDemo(){ jsonStr :=` { "name": "jqw", "age": 18 } `varmapResultmap[string]interface{} err := json.Unmarshal([]byte(jsonStr), &mapResult)iferr !=nil{ ...
先将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"}}, ...
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() ...
先将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 af...