一、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互相转化的更多相关文章

  1. [转]Golang 中使用 JSON 的小技巧

    taowen是json-iterator的作者. 序列化和反序列化需要处理JSON和struct的关系,其中会用到一些技巧. 原文 Golang 中使用 JSON 的小技巧是他的经验之谈,介绍了一些s ...

  2. Golang中Struct与DB中表字段通过反射自动映射 - sqlmapper

    Golang中操作数据库已经有现成的库"database/sql"可以用,但是"database/sql"只提供了最基础的操作接口: 对数据库中一张表的增删改查 ...

  3. Golang中解析json,构造json

    json解析是如今(网络)应用程序开发中最不可或缺的一环了.许多语言需要库支持才可以解析.构造json,但Golang凭借着原生库就可以很好地做到这一点. json的基本表现形式有两个:struct与 ...

  4. 在 golang 中使用 Json

    序列化 序列化对象将使用 encoding/json 中的 Marshal 函数. 函数原型为:func Marshal(v interface{}) ([]byte, error) 以下是官网给出的 ...

  5. 『Golang』在Golang中使用json

    由于要开发一个小型的web应用,而web应用大部分都会使用json作为数据传输的格式,所以有了这篇文章. 包引用 import ( "encoding/json" "gi ...

  6. 在golang中使用json

    jsoniter高性能json库 非常快,支持java和go marshal使用的一些坑 package main import ( "encoding/json" "f ...

  7. JAVA中,JSON MAP LIST的相互转换

    1 JSON包含对象和数组,对应于JAVA中的JSONObject,JSONArray 2 String 转JSON对象 JSONObject.fromObject("String" ...

  8. Go_14:GoLang中 json、map、struct 之间的相互转化

    1. golang 中 json 转 struct <1. 使用 json.Unmarshal 时,结构体的每一项必须是导出项(import field).也就是说结构体的 key 对应的首字母 ...

  9. GoLang中 json、map、struct 之间的相互转化

    1. golang 中 json 转 struct <1. 使用 json.Unmarshal 时,结构体的每一项必须是导出项(import field).也就是说结构体的 key 对应的首字母 ...

随机推荐

  1. Java数据库学习之模糊查询(like )

    Java数据库学习之模糊查询(like ): 第一种方式:直接在SQL语句中进行拼接,此时需要注意的是parm在SQL语句中需要用单引号拼接起来,注意前后单引号之间不能空格 String sql = ...

  2. Centos6.5-dnsmasq安装

    1.使用yum install dnsmasq -y 安装dns(含dns server和dns代理功能) 2.查询dnsmasq已经安装成功 [root@localhost ~]# rpm -q d ...

  3. ADC获取滑块的值(8通道)

    #include "TgcConfig.h"#include "my_usb.h" /************************************* ...

  4. LeetCode_p150_逆波兰表达式计算/后缀表达式计算

    有效的运算符包括 +, -, *, / .每个运算对象可以是整数,也可以是另一个逆波兰表达式. 说明: 整数除法只保留整数部分. 给定逆波兰表达式总是有效的.换句话说,表达式总会得出有效数值且不存在除 ...

  5. 2019春招面试高频题(Java版),持续更新(答案来自互联网)

    第一模块--并发与多线程 Java多线程方法: 实现Runnable接口, 继承thread类, 使用线程池 操作系统层面的进程与线程(对JAVA多线程和高并发有了解吗?) 计算机资源=存储资源+计算 ...

  6. [Java]list集合为空或为null的区别

    判断的是list这个集合的问题,当前需要判断list内值的问题. 简述判断一个list集合是否为空,我们的惯性思维是判断list是否等于null即可,但是在Java中,list集合为空还是为null, ...

  7. IntelliJ IDEA 2018 最新版注册码

    参考:IntelliJ IDEA 2018注册码(无需修改hosts文件) :

  8. html中title小图标的实现

    <link rel="icon" href="picture.ico" type="image/x-icon"/> 注意:图片的 ...

  9. Jetson TX1使用usb camera采集图像 (1)

    使用python实现 https://jkjung-avt.github.io/tx2-camera-with-python/ How to Capture and Display Camera Vi ...

  10. Python Face Detect Offline

    python版本 3.7.0  1. 安装 cmake pip install cmake  2.安装 boost pip install boost  3.安装 dlib pip install d ...