怎么在golang将Struct转换成map
本文章向大家介绍怎么在golang将Struct转换成map,主要包括怎么在golang将Struct转换成map的使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
成都创新互联成立与2013年,先为镶黄等服务建站,镶黄等地企业,进行企业商务咨询服务。为镶黄企业网站制作PC+手机+微官网三网同步一站式服务解决您的所有建站问题。
什么是golang
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的文章就介绍到这了,更多相关的内容请搜索创新互联以前的文章或继续浏览下面的相关文章希望大家以后多多支持创新互联!
网页名称:怎么在golang将Struct转换成map
文章链接:http://scyanting.com/article/jdpeid.html