[转] golang中struct、json、map互相转化
一、Json和struct互换
(1)Json转struct例子:
type People struct {
Name string `json:"name_title"`
Age int `json:"age_size"`
}
func JsonToStructDemo(){
jsonStr := `
{
"name_title": "jqw"
"age_size":12
}
`
var people People
json.Unmarshal([]byte(jsonStr), &people)
fmt.Println(people)
}
func main(){
JsonToStructDemo()
}
输出:
注意json里面的key和struct里面的key要一致,struct中的key的首字母必须大写,而json中大小写都可以。
(2)struct转json
在结构体中引入tag标签,这样匹配的时候json串对应的字段名需要与tag标签中定义的字段名匹配,当然tag中定义的名称不需要首字母大写,且对应的json串中字段名仍然大小写不敏感。此时,结构体中对应的字段名可以不用和匹配的一致,但是首字母必须大写,只有大写才是可对外提供访问的。
例子:
type People struct {
Name string `json:"name_title"`
Age int `json:"age_size"`
}
func StructToJsonDemo(){
p := People{
Name: "jqw",
Age: 18,
}
jsonBytes, err := json.Marshal(p)
if err != nil {
fmt.Println(err)
}
fmt.Println(string(jsonBytes))
}
func main(){
StructToJsonDemo()
}
输出:

二、json和map互转
(1)json转map例子:
func JsonToMapDemo() {
jsonStr := `{"name": "jqw","age": 18}`
var mapResult map[string]interface{}
err := json.Unmarshal([]byte(jsonStr), &mapResult)
if err != nil {
fmt.Println("JsonToMapDemo err: ", err)
}
fmt.Println(mapResult)
}
输出:

(2)map转Json例子
func MapToJsonDemo1(){
mapInstances := []map[string]interface{}{}
instance_1 := map[string]interface{}{"name": "John", "age": 10}
instance_2 := map[string]interface{}{"name": "Alex", "age": 12}
mapInstances = append(mapInstances, instance_1, instance_2)
jsonStr, err := json.Marshal(mapInstances)
if err != nil {
fmt.Println("MapToJsonDemo err: ", err)
}
fmt.Println(string(jsonStr))
}
输出:

例2:
func MapToJsonDemo2(){
b, _ := json.Marshal(map[string]int{"test":1, "try":2})
fmt.Println(string(b))
}
输出:

三、map和struct互转
(1)map转struct
需要安装一个第三方库
在命令行中运行: go get github.com/goinggo/mapstructure
例子:
func MapToStructDemo() {
mapInstance := make(map[string]interface{})
mapInstance["Name"] = "jqw"
mapInstance["Age"] = 18
var people People
err := mapstructure.Decode(mapInstance, &people)
if err != nil {
fmt.Println(err)
}
fmt.Println(people)
}
输出

(2)struct转map例子
func StructToMapDemo(obj interface{}) map[string]interface{}{
obj1 := reflect.TypeOf(obj)
obj2 := reflect.ValueOf(obj)
var data = make(map[string]interface{})
for i := 0; i < obj1.NumField(); i++ {
data[obj1.Field(i).Name] = obj2.Field(i).Interface()
}
return data
}
func TestStructToMap(){
student := Student{10, "jqw", 18}
data := StructToMapDemo(student)
fmt.Println(data)
}
输出:
---------------------
作者:小拳头
来源:CSDN
原文:https://blog.csdn.net/xiaoquantouer/article/details/80233177
版权声明:本文为博主原创文章,转载请附上博文链接!
[转] golang中struct、json、map互相转化的更多相关文章
- [转]Golang 中使用 JSON 的小技巧
taowen是json-iterator的作者. 序列化和反序列化需要处理JSON和struct的关系,其中会用到一些技巧. 原文 Golang 中使用 JSON 的小技巧是他的经验之谈,介绍了一些s ...
- Golang中Struct与DB中表字段通过反射自动映射 - sqlmapper
Golang中操作数据库已经有现成的库"database/sql"可以用,但是"database/sql"只提供了最基础的操作接口: 对数据库中一张表的增删改查 ...
- Golang中解析json,构造json
json解析是如今(网络)应用程序开发中最不可或缺的一环了.许多语言需要库支持才可以解析.构造json,但Golang凭借着原生库就可以很好地做到这一点. json的基本表现形式有两个:struct与 ...
- 在 golang 中使用 Json
序列化 序列化对象将使用 encoding/json 中的 Marshal 函数. 函数原型为:func Marshal(v interface{}) ([]byte, error) 以下是官网给出的 ...
- 『Golang』在Golang中使用json
由于要开发一个小型的web应用,而web应用大部分都会使用json作为数据传输的格式,所以有了这篇文章. 包引用 import ( "encoding/json" "gi ...
- 在golang中使用json
jsoniter高性能json库 非常快,支持java和go marshal使用的一些坑 package main import ( "encoding/json" "f ...
- JAVA中,JSON MAP LIST的相互转换
1 JSON包含对象和数组,对应于JAVA中的JSONObject,JSONArray 2 String 转JSON对象 JSONObject.fromObject("String" ...
- Go_14:GoLang中 json、map、struct 之间的相互转化
1. golang 中 json 转 struct <1. 使用 json.Unmarshal 时,结构体的每一项必须是导出项(import field).也就是说结构体的 key 对应的首字母 ...
- GoLang中 json、map、struct 之间的相互转化
1. golang 中 json 转 struct <1. 使用 json.Unmarshal 时,结构体的每一项必须是导出项(import field).也就是说结构体的 key 对应的首字母 ...
随机推荐
- Spring Boot报错 MultipartException The temporary upload...
Spring Boot报错:尤其是在处理Ribbon这类接口调用型的负载均衡组件,常见问题 ERROR o.a.c.c.C.[.[.[.[dispatcherServlet] - Servlet.se ...
- Python基础7:字符串方法
1 * 重复输出字符串 print('helo '*4) 2 [],[:] 通过索引获取字符串中的字符,这里和列表中的切片操作是相同的,具体内容见列表 print('hello word'[2:]) ...
- 20165223《网络对抗技术》Exp3 免杀原理与实践
目录 -- 免杀原理与实践 免杀原理与实践 本次实验任务 基础知识问答 免杀扫描引擎 实验内容 正确使用msf编码器,msfvenom生成jar等文件,veil-evasion,加壳工具,使用shel ...
- EC20 R2.1
1.模块开机成功前WAKEUP_IN. NET_MODE. BT_CTS. COEX_UART_TX(背部焊盘). COEX_UART_RX(背部焊盘) 和WLAN_EN(背部焊盘)引脚禁止上拉. 2 ...
- Tensorflow计算正确率、精确率、召回率
二分类模型的评价指标 https://www.cnblogs.com/xiaoniu-666/p/10511694.html 参考tf的方法 predictions = tf.argmax(predi ...
- Spring项目使用Junit4测试配置
我们经常要写junit测试,在不启动整个web项目的情况下,测试自己的service实现或者是dao实现,我们来充分利用下junit4的强大功能. 1.junit4的测试类 import java.u ...
- Tomcat系列(10)——Tomcat主要设计模式5种(外观,责任链,观察者,模板方法,命令模式)
核心部分 外观模式: RequestFacade应用门面模式(facade)来封装HttpServletRequest. 观察者模式: 事件监听机制,控制组件生命周期的 Lifecycle .Serv ...
- 树莓派安装 MySQL 时出现错误的解决方法
今天被要求解决一个树莓派无法正常安装 MySQL 的问题.以下是解决过程记录. 我在 Mac 上利用 SSH 连接到树莓派,执行 sudo apt-get install mysql-server m ...
- H5_0008:链接分享图片和判断平台
<!--分享图片--><div id="share_img" style="display:none;"><img class=& ...
- python中__str__与__repr__的区别
__str__和repr __str__和__repr__都是python的内置方法,都用与将对象的属性转化成人类容易识别的信息,他们有什么区别呢 来看一段代码 from math import hy ...