您好,登录后才能下订单哦!
本文章向大家介绍怎么在golang将Struct转换成map,主要包括怎么在golang将Struct转换成map的使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
golang 是Google开发的一种静态强类型、编译型、并发型,并具有垃圾回收功能的编程语言,其语法与 C语言相近,但并不包括如枚举、异常处理、继承、泛型、断言、虚函数等功能。
mport ( "encoding/json" "fmt" "reflect" "time" ) type Persion struct { Id int Name string Address string Email string School string City string Company string Age int Sex string Proviece string Com string PostTo string Buys string Hos string } func main() { StructToMapViaJson() //StructToMapViaReflect() } func StructToMapViaJson() { m := make(map[string]interface{}) t := time.Now() person := Persion{ Id: 98439, Name: "zhaondifnei", Address: "大沙地", Email: "dashdisnin@126.com", School: "广州第十五中学", City: "zhongguoguanzhou", Company: "sndifneinsifnienisn", Age: 23, Sex: "F", Proviece: "jianxi", Com: "广州兰博基尼", PostTo: "蓝鲸XXXXXXXX", Buys: "shensinfienisnfieni", Hos: "zhonsndifneisnidnfie", } j, _ := json.Marshal(person) json.Unmarshal(j, &m) fmt.Println(m) fmt.Println(time.Now().Sub(t)) }
一、通过struct转json,json转成map
func StructToMapViaJson() { m := make(map[string]interface{}) t := time.Now() person := Persion{ Id: 98439, Name: "zhaondifnei", Address: "大沙地", Email: "dashdisnin@126.com", School: "广州第十五中学", City: "zhongguoguanzhou", Company: "sndifneinsifnienisn", Age: 23, Sex: "F", Proviece: "jianxi", Com: "广州兰博基尼", PostTo: "蓝鲸XXXXXXXX", Buys: "shensinfienisnfieni", Hos: "zhonsndifneisnidnfie", } j, _ := json.Marshal(person) json.Unmarshal(j, &m) fmt.Println(m) fmt.Printf("duration:%d", time.Now().Sub(t)) }
output:
map[Proviece:jianxi Com:广州兰博基尼 Hos:zhonsndifneisnidnfie Name:zhaondifnei Company:sndifneinsifnienisn Buys:shensinfienisnfieni Age:23 PostTo:蓝鲸XXXXXXXX Address:大沙地 School:广州第十五中学 City:zhongguoguanzhou Sex:F Id:98439 Email:dashdisnin@126.com]
duration:250467
二、通过反射形式生成map
func StructToMapViaReflect() { m := make(map[string]interface{}) t := time.Now() person := Persion{ Id: 98439, Name: "zhaondifnei", Address: "大沙地", Email: "dashdisnin@126.com", School: "广州第十五中学", City: "zhongguoguanzhou", Company: "sndifneinsifnienisn", Age: 23, Sex: "F", Proviece: "jianxi", Com: "广州兰博基尼", PostTo: "蓝鲸XXXXXXXX", Buys: "shensinfienisnfieni", Hos: "zhonsndifneisnidnfie", } elem := reflect.ValueOf(&person).Elem() relType := elem.Type() for i := 0; i < relType.NumField(); i++ { m[relType.Field(i).Name] = elem.Field(i).Interface() } fmt.Println(m) fmt.Printf("duration:%d", time.Now().Sub(t)) }
output:
map[Buys:shensinfienisnfieni Name:zhaondifnei City:zhongguoguanzhou Sex:F Proviece:jianxi Com:广州兰博基尼 Id:98439 School:广州第十五中学 Address:大沙地 Age:23 PostTo:蓝鲸XXXXXXXX Hos:zhonsndifneisnidnfie Email:dashdisnin@126.com Company:sndifneinsifnienisn]
duration:104239
到此这篇关于怎么在golang将Struct转换成map的文章就介绍到这了,更多相关的内容请搜索亿速云以前的文章或继续浏览下面的相关文章希望大家以后多多支持亿速云!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。