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
13.965µs
map[address:[{Address:湖南} {Address:北京}] id:01 username:酒窝猪]--- PASS: TestStructToMapByReflect (0.00s)
PASS
总结
问题:论性能哪个更佳?
答案是使用反射的效果更快点,没有那么多繁琐的转换,记住在 make 中进行初始化大小,我试了下,不指定大小与指定大小时间上有 3~4µs 的区别
网络上还有一种方法是使用 structs 包,不过我看了下,该依赖包已经三年没更新了
二、struct, json 互转
1. struct 转 json
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)扩容机制的原理
- 上一篇
- 浅谈Golang 切片(slice)扩容机制的原理
- 下一篇
- go web 处理表单的输入的说明
-
- Golang · Go教程 | 50分钟前 | 文件处理 · go · archive/zip · archive/zip ZIP下载 Go文件打包
- Go 怎么把多个文件打包成 ZIP 并提供下载
- 316浏览 收藏
-
- Golang · Go教程 | 1小时前 | HTTP · go · 文件上传 · 安全 · 文件上传 Go mime/multipart MaxBytesReader
- Go 文件上传怎么限制大小并保存原始文件名
- 254浏览 收藏
-
- Golang · Go教程 | 1小时前 |
- Go 怎么逐行读取大 CSV 文件并记录错误行
- 171浏览 收藏
-
- Golang · Go教程 | 14小时前 |
- Go 结构体标签读取不一致:用 StructTag.Get 区分缺失键、空值与格式错误
- 423浏览 收藏
-
- Golang · Go教程 | 19小时前 |
- Go 私有模块在 CI 里突然走代理:用 GOPRIVATE、GONOSUMDB 和 GOPROXY 分开排查
- 339浏览 收藏
-
- Golang · Go教程 | 19小时前 | govulncheck · Go安全 · govulncheck Go漏洞扫描 source模式 binary模式
- Go govulncheck 结果怎么看不误判:source 模式与 binary 模式各自能证明什么
- 142浏览 收藏
-
- Golang · Go教程 | 19小时前 | 依赖管理 · go · 模块版本 · Go MVS go list Go Modules
- Go 依赖升级后仍命中旧版本:用 go list -m all 还原 MVS 选择结果
- 462浏览 收藏
-
- Golang · Go教程 | 19小时前 |
- govulncheck 为什么有的漏洞只出现在测试:按扫描范围拆分依赖风险
- 189浏览 收藏
-
- Golang · Go教程 | 20小时前 | 依赖管理 · Go Modules · 排障 · Go replace go.mod go list
- Go replace 看似生效却仍下载远程模块:用 go list -m -json 查真实来源
- 409浏览 收藏
-
- Golang · Go教程 | 20小时前 |
- govulncheck 报告里的 symbol 是什么:从入口函数追到可达漏洞代码
- 151浏览 收藏
-
- Golang · Go教程 | 23小时前 |
- Go 服务 CPU 高还是内存涨:按症状选择 pprof profile 并验证热点
- 314浏览 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 485次学习
-
- SuperCLUE
- SuperCLUE是权威的中文大语言模型综合评测基准,涵盖语言理解、知识应用、AI Agent智能体及安全性等12项核心能力。通过多轮对话与客观测试,定期发布榜单与技术报告,为模型研发、优化及行业选型提供科学依据。
- 145次使用
-
- C-Eval
- 深入了解C-Eval中文评估套件,涵盖52个学科与4级难度。本文详解其功能特点、Zero-shot/Few-shot使用方法及代码示例,助您全面评测LLM中文理解与泛化能力。
- 68次使用
-
- ClickPrompt
- ClickPrompt是一款专为AI提示词编写者设计的开源在线工具,支持Stable Diffusion绘图、ChatGPT对话及GitHub Copilot代码辅助。提供Prompt自动生成、一键运行、社区分享及可视化优化功能,帮助用户高效获取精准AI输出。
- 35次使用
-
- PromptHero
- PromptHero是专业的AI提示词搜索引擎与优化平台,支持Stable Diffusion、Midjourney等主流模型。提供海量提示词库、分类搜索、在线课程及社区互动,助力用户高效生成高质量AI图像与文本。
- 10次使用
-
- Stable Diffusion Prompt Book
- 深入解析OpenArt推出的Stable Diffusion Prompt Book,这本免费的开源提示词指南涵盖从基础语法到高级技巧,提供风格化词库与参数建议,助您优化AI绘画生成效果。
- 21次使用
-
- 接口返回 200 但前端仍报错怎么办:从响应格式到跨域一步步排查
- 2026-06-14 332浏览
-
- Go map 并发写 panic 怎么办:从共享 map 到可控写入路径
- 2026-06-30 123浏览
-
- 详解如何在Go语言中循环数据结构
- 2022-12-22 406浏览
-
- 一文带你搞懂Golang结构体内存布局
- 2022-12-22 125浏览
-
- Golang中map的深入探究
- 2022-12-23 369浏览

