当前位置:网站首页>Go语言JSON包使用
Go语言JSON包使用
2022-04-23 17:51:00 【刘远山】
目录

序列化与反序列化
1、序列化
1)结构体数据转JSON,属性必须是公有的大写开头
使用Person结构体描述用户信息并转JSON
package main
import (
"encoding/json"
"fmt"
)
type Person struct {
Name string
Age int
Rmb float64
Sex bool
Hobby []string
}
func main() {
person := Person{
"于谦", 50, 123.45, true, []string{
"抽烟", "喝酒", "烫头"}}
bytes, e := json.Marshal(person)
if e != nil {
fmt.Println("序列化失败,err=", e)
return
}
fmt.Println(string(bytes))
}
2)Map数据转JSON
使用map[string]interface{}描述用户信息并转JSON
package main
import (
"encoding/json"
"fmt"
)
func main() {
dataMap := make(map[string]interface{
})
dataMap["name"] = "于谦"
dataMap["age"] = 50
dataMap["rmb"] = 123.45
dataMap["sex"] = true
dataMap["hobby"] = []string{
"抽烟", "喝酒", "烫头"}
bytes, e := json.Marshal(dataMap)
if e != nil {
fmt.Println("序列化失败,err=", e)
return
}
fmt.Println(string(bytes))
}
3)map切片数据转JSON
使用map切片描述多个用户信息并转JSON
package main
import (
"encoding/json"
"fmt"
)
func main() {
dataMap1 := make(map[string]interface{
})
dataMap1["name"] = "王钢蛋"
dataMap1["hobby"] = []string{
"抽中华", "喝牛栏山", "烫花卷头"}
dataMap2 := make(map[string]interface{
})
dataMap2["name"] = "王铁蛋"
dataMap2["hobby"] = []string{
"抽玉溪", "喝五粮液", "烫杀马特"}
dataMap3 := make(map[string]interface{
})
dataMap3["name"] = "王铜蛋"
dataMap3["hobby"] = []string{
"抽小熊猫", "喝剑南春", "烫鸡冠头"}
dataSlice := make([]map[string]interface{
}, 0)
dataSlice = append(dataSlice, dataMap1, dataMap2, dataMap3)
bytes, e := json.Marshal(dataSlice)
if e != nil {
fmt.Println("序列化失败,err=", e)
return
}
fmt.Println(string(bytes))
}
2、反序列化
1)JSON转结构体数据
package main
import (
"encoding/json"
"fmt"
)
var jsonStr = `{"Name":"于谦","Age":50,"Rmb":123.45,"Sex":true,"Hobby":["抽烟","喝酒","烫头"]}`
func main() {
type Person struct {
Name string
Age int
Rmb float64
Sex bool
Hobby []string
}
jsonBytes := []byte(jsonStr)
personPtr := new(Person)
err := json.Unmarshal(jsonBytes, personPtr)
if err != nil {
fmt.Println("反序列化失败,err=", err)
return
}
fmt.Println(*personPtr)
}
2)JSON转map数据
package main
import (
"encoding/json"
"fmt"
)
var jsonStr = `{"Name":"于谦","Age":50,"Rmb":123.45,"Sex":true,"Hobby":["抽烟","喝酒","烫头"]}`
func main() {
jsonBytes := []byte(jsonStr)
dataMap := make(map[string]interface{
})
err := json.Unmarshal(jsonBytes, &dataMap)
if err != nil {
fmt.Println("反序列化失败,err=", err)
return
}
fmt.Println(dataMap)
}
3)JSON转切片数据
package main
import (
"encoding/json"
"fmt"
)
func main() {
jsonStr := `[{"hobby":["抽中华","喝牛栏山","烫花卷头"],"name":"王钢蛋"},{"hobby":["抽玉溪","喝五粮液","烫杀马特"],"name":"王铁蛋"},{"hobby":["抽小熊猫","喝剑南春","烫鸡冠头"],"name":"王铜蛋"}]`
jsonBytes := []byte(jsonStr)
dataSlice := make([]map[string]interface{
}, 0)
err := json.Unmarshal(jsonBytes, &dataSlice)
if err != nil {
fmt.Println("反序列化失败,err=", err)
return
}
fmt.Println(dataSlice)
}
读写JSON文件
1、编码
1)将map数据转为JSON编码数据写入到JSON文件中
package main
import (
"encoding/json"
"fmt"
"os"
)
func main() {
dataMap := make(map[string]interface{
})
dataMap["name"] = "于谦"
dataMap["age"] = 50
dataMap["rmb"] = 123.45
dataMap["sex"] = true
dataMap["hobby"] = []string{
"抽烟", "喝酒", "烫头"}
//创建并打开目标JSON文件
dstFile, _ := os.OpenFile("D:/go_work/src/demo/1.json", os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0666)
defer dstFile.Close()
//创建目标文件的编码器
encoder := json.NewEncoder(dstFile)
//将Go语言数据编码到JSON文件
err := encoder.Encode(dataMap)
//判断编码是否成功
if err != nil {
fmt.Println("编码数据到JSON文件失败,err=", err)
return
}
fmt.Println("编码成功!")
}
2)将结构体切片数据转为JSON编码数据写入到JSON文件中
package main
import (
"encoding/json"
"fmt"
"os"
)
func main() {
type Person struct {
Name string
Age int
Rmb float64
Sex bool
Hobby []string
}
p1 := Person{
"王钢蛋", 30, 123.45, false, []string{
"抽中华", "喝农夫山泉", "烫芋头"}}
p2 := Person{
"王铁蛋", 30, 123.45, false, []string{
"抽玉溪", "喝乐百氏", "烫手"}}
p3 := Person{
"王铜蛋", 30, 123.45, false, []string{
"抽黄金叶", "喝三鹿牛奶", "烫光头"}}
people := make([]Person, 0)
people = append(people, p1, p2, p3)
dstFile, _ := os.OpenFile("D:/go_work/src/demo/2.json", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
defer dstFile.Close()
encoder := json.NewEncoder(dstFile)
err := encoder.Encode(people)
//判断编码是否成功
if err != nil {
fmt.Println("编码数据到JSON文件失败,err=", err)
return
}
fmt.Println("编码成功!")
}
2、解码
1)将JSON文件中的数据读取成map数据
package main
import (
"encoding/json"
"fmt"
"os"
)
func main() {
//打开存储JSON数据的源文件
srcFile, _ := os.Open("D:/go_work/src/demo/1.json")
defer srcFile.Close()
//创建map,用于接收解码好的数据
dataMap := make(map[string]interface{
})
//创建源文件的解码器
decoder := json.NewDecoder(srcFile)
//解码源文件中的数据,丢入dataMap所在的内存
err := decoder.Decode(&dataMap)
//获取解码结果
if err != nil {
fmt.Println("解码失败,err=", err)
return
}
fmt.Println("解码成功:", dataMap)
}
fmt.Println("解码成功:", dataMap)
}
2)将JSON文件中的数据读取成切片数据
要注意数据是否适合转切片
package main
import (
"encoding/json"
"fmt"
"os"
)
func main() {
type Person struct {
Name string
Age int
Rmb float64
Sex bool
Hobby []string
}
//打开存储JSON数据的源文件
srcFile, _ := os.Open("D:/go_work/src/demo/2.json")
defer srcFile.Close()
//创建用于接数据的变量
people := make([]Person, 0)
//创建源文件的解码器
decoder := json.NewDecoder(srcFile)
//解码源文件中的数据,丢入dataMap所在的内存
err := decoder.Decode(&people)
//获取解码结果
if err != nil {
fmt.Println("解码失败,err=", err)
return
}
fmt.Println("解码成功:", people)
}
版权声明
本文为[刘远山]所创,转载请带上原文链接,感谢
https://blog.csdn.net/weixin_39218464/article/details/124352497
边栏推荐
猜你喜欢

超分之TDAN

Halo 开源项目学习(二):实体类与数据表

102. Sequence traversal of binary tree

Hcip fifth experiment

394. String decoding - auxiliary stack

【Appium】通过设计关键字驱动文件来编写脚本

JS parsing and execution process

Cloud native Virtualization: building edge computing instances based on kubevirt

EasymodbusTCP之clientexample解析

Client example analysis of easymodbustcp
随机推荐
470. Rand10() is implemented with rand7()
Gaode map search, drag and drop query address
Anchor location - how to set the distance between the anchor and the top of the page. The anchor is located and offset from the top
Add animation to the picture under V-for timing
Type judgment in [untitled] JS
C1小笔记【任务训练篇一】
MySQL进阶之索引【分类,性能分析,使用,设计原则】
Dry goods | how to extract thumbnails quickly?
Use of list - addition, deletion, modification and query
Gets the time range of the current week
ES6 face test questions (reference documents)
Sword finger offer 22 The penultimate node in the linked list - speed pointer
Timestamp to formatted date
列錶的使用-增删改查
Summary of common SQL statements
239. Maximum value of sliding window (difficult) - one-way queue, large top heap - byte skipping high frequency problem
关于gcc输出typeid完整名的方法
2022年上海市安全员C证操作证考试题库及模拟考试
2021长城杯WP
239. 滑动窗口最大值(困难)-单向队列、大顶堆-字节跳动高频题