golang struct, map, json之间的相互转换
对于一个Golang开发者来说,牢固扎实的基础是十分重要的,golang学习网就来带大家一点点的掌握基础知识点。今天本篇文章带大家了解《golang struct, map, json之间的相互转换》,主要介绍了map、Struct、JSON,希望对大家的知识积累有所帮助,快点收藏起来吧,否则需要时就找不到了!
本文用于记录我在 golang 学习阶段遇到的类型转换问题,针对的是 json 、map、struct 之间相互转换的问题,用到的技术 json 、mapstructure、reflect 三个类库
公共代码区域
package main import ( "encoding/json" "fmt" "testing" ) type UserInfoVo struct { Id string `json:"id"` UserName string `json:"user_name"` Address []AddressVo `json:"address"` } type AddressVo struct { Address string `json:"address"` } var beforeMap = map[string]interface{}{ "id": "123", "user_name": "酒窝猪", "address": []map[string]interface{}{{"address": "address01"}, {"address": "address02"}}, } var User UserInfoVo func init() { User = UserInfoVo{ Id: "01", UserName: "酒窝猪", Address: []AddressVo{ { Address: "湖南", }, { Address: "北京", }, }, } }
一、map, struct 互转
1.map 转 struct
map 转 struct 有两种方式
1.是通过第三方包 github.com/mitchellh/mapstructure
2.通过 map 转 json,再通过 json 转 struct
第三方包 mapstructure
下载依赖,通过第三方依赖进行转换
go get github.com/goinggo/mapstructure
func TestMapToStructByMod(t *testing.T) { var afterStruct =UserInfoVo{} before := time.Now() err := mapstructure.Decode(beforeMap, &afterStruct) if err!=nil{ fmt.Println(err) } fmt.Printf("result:%+v \n",time.Since(before)) fmt.Printf("result:%+v \n",afterStruct) }
result:61.757µs
result:{Id:123 UserName: Address:[{Address:address01} {Address:address02}]}
--- PASS: TestMapToStructByMod (0.00s)
PASS
通过 JSON 进行转换
先将 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 afterStruct =UserInfoVo{} before := time.Now() marshal, err := json.Marshal(beforeMap) if err!=nil{ fmt.Println("marshal:",err) return } err = json.Unmarshal(marshal, &afterStruct) if err!=nil{ fmt.Println("unmarshal:",err) return } fmt.Println(time.Since(before)) fmt.Printf("resutlt: %+v",afterStruct) }
134.299µs
resutlt: {Id:123 UserName:酒窝猪 Address:[{Address:address01} {Address:address02}]}--- PASS: TestMapToStructByJson (0.00s)
PASS
总结
问题:
论性能哪个更佳?
根据结果答案
使用 JSON 需要时间是 134.299µs
使用 mapstructure 需要时间是 61.757µs
结果是使用第三方包 mapstructure 性能更好,那么,是因为什么呢?暂且按下不表
2、struct 转 map
JSON 序列化转换
先将 struct 转换成字节数组,再将字节数组转换成 map 打印
func TestStructToMapByJson(t *testing.T) { var resultMap interface{} before := time.Now() jsonMarshal, _ := json.Marshal(User) err := json.Unmarshal(jsonMarshal, &resultMap) if err != nil { fmt.Println(err) return } fmt.Println(time.Since(before)) fmt.Printf("%+v",resultMap) }
158.857µs
map[address:[map[address:湖南] map[address:北京]] id:01 user_name:酒窝猪]--- PASS: TestStructToMapByJson (0.00s)
PASS
通过反射转换
通过反射获取 User 的类型与值
func TestStructToMapByReflect(t *testing.T) { var resultMap = make(map[string]interface{},10) before := time.Now() ty:=reflect.TypeOf(User) v:=reflect.ValueOf(User) for i := 0; i <blockquote> <p>13.965µs<br> map[address:[{Address:湖南} {Address:北京}] id:01 username:酒窝猪]--- PASS: TestStructToMapByReflect (0.00s)<br> PASS</p> </blockquote> <p>总结<br> 问题:论性能哪个更佳?</p> <p>答案是使用反射的效果更快点,没有那么多繁琐的转换,记住在 make 中进行初始化大小,我试了下,不指定大小与指定大小时间上有 3~4µs 的区别<br> 网络上还有一种方法是使用 structs 包,不过我看了下,该依赖包已经三年没更新了</p> <h2>二、struct, json 互转<br></h2> <p>1. struct 转 json<br></p> <pre class="brush:plain;"> func TestStructToJsonByJson(t *testing.T) { before := time.Now() marshal, _ := json.Marshal(User) fmt.Println(time.Since(before)) fmt.Printf("%s", marshal) }
116.068µs
{"id":"01","user_name":"酒窝猪","address":[{"address":"湖南"},{"address":"北京"}]}--- PASS: TestStructToJsonByJson (0.00s)
PASS
2.json 转 struct
func TestJsonToStructByJson(t *testing.T) { info:=UserInfoVo{} marshal, _ := json.Marshal(User) before := time.Now() json.Unmarshal(marshal,&info) fmt.Println(time.Since(before)) fmt.Printf("%+v",info) }
23.009µs
{Id:01 UserName:酒窝猪 Address:[{Address:湖南} {Address:北京}]}--- PASS: TestJsonToStructByJson (0.00s)
PASS
三、map, json 互转
1.map 转 json
func TestMapToJson(t *testing.T) { before := time.Now() marshal, _ := json.Marshal(beforeMap) fmt.Println(time.Since(before)) fmt.Printf("%s", marshal) }
75.133µs
{"address":[{"address":"address01"},{"address":"address02"}],"id":"123","user_name":"酒窝猪"}--- PASS: TestMapToJson (0.00s)
PASS
2.json 转 map
func TestJsonToMap(t *testing.T) { marshal, _ := json.Marshal(beforeMap) resultMap:=make(map[string]interface{},10) before := time.Now() json.Unmarshal(marshal,&resultMap) fmt.Println(time.Since(before)) fmt.Printf("%+v", resultMap) }
28.728µs
map[address:[map[address:address01] map[address:address02]] id:123 user_name:酒窝猪]--- PASS: TestJsonToMap (0.00s)
PASS
总结
三者之间的转换更多的是关于如果使用 json 内库,只有在 map 转 struct 使用了 mapstructure,struct 转 map 使用了反射,其他转换,更多的是使用 json 内置库进行转换
以上就是《golang struct, map, json之间的相互转换》的详细内容,更多关于golang的资料请关注golang学习网公众号!

- 上一篇
- 浅谈Golang 切片(slice)扩容机制的原理

- 下一篇
- go web 处理表单的输入的说明
-
- Golang · Go教程 | 12分钟前 |
- Vim配置Go环境:语法高亮与文件类型设置
- 285浏览 收藏
-
- Golang · Go教程 | 18分钟前 |
- Golang构建微服务与JWTRedis方案
- 452浏览 收藏
-
- Golang · Go教程 | 37分钟前 |
- Golang反射与泛型对比解析
- 389浏览 收藏
-
- Golang · Go教程 | 38分钟前 |
- Golang构建云原生API网关教程
- 465浏览 收藏
-
- Golang · Go教程 | 41分钟前 |
- Golang并发爬虫:worker池与任务分发解析
- 382浏览 收藏
-
- Golang · Go教程 | 47分钟前 |
- GolangJSONAPI测试与数据验证教程
- 151浏览 收藏
-
- Golang · Go教程 | 48分钟前 |
- Golang开发ArgoCD插件教程详解
- 237浏览 收藏
-
- Golang · Go教程 | 54分钟前 |
- Go语言30行代码搭建代理服务器教程
- 179浏览 收藏
-
- Golang · Go教程 | 57分钟前 |
- Golang连接MySQL数据库教程
- 127浏览 收藏
-
- Golang · Go教程 | 1小时前 |
- Go语言文件逐行读取转字符串方法
- 418浏览 收藏
-
- Golang · Go教程 | 1小时前 |
- Golang并发安全:Mutex与RWMutex对比分析
- 196浏览 收藏
-
- Golang · Go教程 | 1小时前 |
- GolangTCP粘包处理与自定义协议详解
- 405浏览 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 542次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 511次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 498次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 484次学习
-
- 千音漫语
- 千音漫语,北京熠声科技倾力打造的智能声音创作助手,提供AI配音、音视频翻译、语音识别、声音克隆等强大功能,助力有声书制作、视频创作、教育培训等领域,官网:https://qianyin123.com
- 92次使用
-
- MiniWork
- MiniWork是一款智能高效的AI工具平台,专为提升工作与学习效率而设计。整合文本处理、图像生成、营销策划及运营管理等多元AI工具,提供精准智能解决方案,让复杂工作简单高效。
- 88次使用
-
- NoCode
- NoCode (nocode.cn)是领先的无代码开发平台,通过拖放、AI对话等简单操作,助您快速创建各类应用、网站与管理系统。无需编程知识,轻松实现个人生活、商业经营、企业管理多场景需求,大幅降低开发门槛,高效低成本。
- 101次使用
-
- 达医智影
- 达医智影,阿里巴巴达摩院医疗AI创新力作。全球率先利用平扫CT实现“一扫多筛”,仅一次CT扫描即可高效识别多种癌症、急症及慢病,为疾病早期发现提供智能、精准的AI影像早筛解决方案。
- 95次使用
-
- 智慧芽Eureka
- 智慧芽Eureka,专为技术创新打造的AI Agent平台。深度理解专利、研发、生物医药、材料、科创等复杂场景,通过专家级AI Agent精准执行任务,智能化工作流解放70%生产力,让您专注核心创新。
- 92次使用
-
- 详解如何在Go语言中循环数据结构
- 2022-12-22 406浏览
-
- 一文带你搞懂Golang结构体内存布局
- 2022-12-22 125浏览
-
- Golang中map的深入探究
- 2022-12-23 369浏览
-
- Golang中map数据类型的使用方法
- 2022-12-30 443浏览
-
- golangmap的基本操作及定义方式
- 2023-01-08 134浏览