[转] 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 对应的首字母 ...
随机推荐
- Appium环境搭建-精简版
Appium自动化环境准备 安装配置JDK 下载Android SDK并配置环境变量 安装模拟器或连接真机 安装appium desktop 安装python和pycharm (开发语言和开发工具) ...
- [UVa-437] Color Length
无法用复杂状态进行转移时改变计算方式:巧妙的整体考虑:压缩空间优化时间 传送门:$>here<$ 题意 给出两个字符串a,b,可以将他们穿插起来(相对位置不变).要求最小化ΣL(c),其中 ...
- 数论ex
数论ex 数学学得太差了补补知识点or复习 Miller-Rabin 和 Pollard Rho Miller-Rabin 前置知识: 费马小定理 \[ a^{p-1}\equiv 1\pmod p, ...
- 题解:YNOI/GZOI2019 与或和
题目大意: 1. 求所有的子矩阵的and之和2. 求所有子矩阵的or之和 由于是位运算,那么久直接拆位,于是就变成了求全0子矩阵的个数和全1子矩阵的个数那么题目就变成了简单的单调栈问题 #includ ...
- msyql存储数据时字段被截断
关于mysql中字段类型为text文本存储json格式数据,字段被截断的问题 背景: 字段类型 MEDIUMTEXT 确定存储内容5548个字符,换算为字节不超过16M 数据库内已经存在更长内容的存储 ...
- 夜神模拟器调试web APP
前言:之前工作之余的时间自己做了一个web APP,但是都是在浏览器上调试的,这次想看看在手机上啥效果,所以下载了一个夜神模拟器 一.下载夜神模拟器 https://www.yeshen.com/ 二 ...
- The 16th Zhejiang Provincial Collegiate Programming Contest Sponsored E.Sequence in the Pocket(思维题)
传送门 题意: 给出一个序列,你可以将任意一个数移到最前面: 求最少需要移动多少次,可以是此序列变成非递减序列: 思路: 定义 (ai,aj) 为逆序对 ( i < j , ai > aj ...
- SVG---DEMO
SVG代码: <svg id="circle" data-name="circle_1" xmlns="http://www.w3.org/20 ...
- Mysql查询库、表存储量(Size)
Mysql查询库.表存储量(Size) 1.要查询表所占的容量,就是把表的数据和索引加起来就可以了. SELECT SUM(DATA_LENGTH) + SUM(INDEX_LENGTH) FROM ...
- 实时通讯系列目录篇之SignalR详解
一. 简单说几句 最早使用SignalR的时候大约是两年前了,记得当时是一个OA中消息的实时提醒,轮询的方式有点耗资源,WebSocket写起来又比较麻烦,最终选择了SignalR,当时是什么版本已经 ...