当前位置:网站首页>Go语言JSON 处理
Go语言JSON 处理
2022-06-23 09:36:00 【51CTO】
JSON字符串解析到结构体
代码示例
type User struct {
Name string
FansCount int64
}
// 如果反序列化的时候指定明确的结构体和变量类型
func TestJsonUnmarshal(t *testing.T) {
const jsonStream = `
{"name":"ethancai", "fansCount": 9223372036854775807}
`
var user User // 类型为User
err := JsonUnmarshal(jsonStream,
&user)
if err != nil {
fmt.Println("error:", err)
}
fmt.Printf("%+v \n", user)
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
解析Json数组到切片(数组)
type Person struct {
Name string
Age int
}
type Family struct {
Persons []Person
}
// 解析多维数组
var f Family
// 模拟传输的Json数据
familyJSON := `{"Persons": [{"Name":"Elinx","Age":26}, {"Name":"Twinkle","Age":21}] }`
fmt.Println("======================")
// 解析字符串为Json
json.Unmarshal([]byte(familyJSON),
&f)
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
运行结果
使用 struct tag 辅助构建 json
struct能被转换的字段都是首字母大写的字段,但如果想要在json中使用小写字母开头的key,可以使用struct的tag来辅助反射。
type Post struct {
Id int `json:"ID"`
Content string `json:"content"`
Author string `json:"author"`
Label []string `json:"label"`
}
func TestJsonMash1(t *testing.T){
postp :=
&Post{
2,
"Hello World",
"userB",
[]string{"linux", "shell"},
}
p, _ := json.MarshalIndent(postp, "", "\t")
fmt.Println(string(p))
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
运行结果:
如何使用 tag
- tag中标识的名称将称为json数据中key的值
- tag可以设置为
json:"-"来表示本字段不转换为json数据,即使这个字段名首字母大写 - 如果想要json key的名称为字符"-",则可以特殊处理
json:"-,",也就是加上一个逗号 - 如果tag中带有
,omitempty选项,那么如果这个字段的值为0值,即false、0、""、nil等,这个字段将不会转换到json中 - 如果字段的类型为bool、string、int类、float类,而tag中又带有
,string选项,那么这个字段的值将转换成json字符串
解析 Json 数据到结构已知 struct
{
"id": 1,
"content": "hello world",
"author": {
"id": 2,
"name": "userA"
},
"published": true,
"label": [],
"nextPost": null,
"comments": [{
"id": 3,
"content": "good post1",
"author": "userB"
},
{
"id": 4,
"content": "good post2",
"author": "userC"
}
]
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
测试代码
type Post struct {
ID int64 `json:"id"`
Content string `json:"content"`
Author Author `json:"author"`
Published bool `json:"published"`
Label []string `json:"label"`
NextPost *Post `json:"nextPost"`
Comments []*Comment `json:"comments"`
}
type Author struct {
ID int64 `json:"id"`
Name string `json:"name"`
}
type Comment struct {
ID int64 `json:"id"`
Content string `json:"content"`
Author string `json:"author"`
}
func TestJsonStruct(t *testing.T){
jsonData :="{\n \"id\": 1,\n \"content\": \"hello world\",\n \"author\": {\n \"id\": 2,\n \"name\": \"userA\"\n },\n \"published\": true,\n \"label\": [],\n \"nextPost\": null,\n \"comments\": [{\n \"id\": 3,\n \"content\": \"good post1\",\n \"author\": \"userB\"\n },\n {\n \"id\": 4,\n \"content\": \"good post2\",\n \"author\": \"userC\"\n }\n ]\n}"
var post Post
// 解析json数据到post中
err := json.Unmarshal([]byte(jsonData),
&post)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(post)
fmt.Println(post.Author, post.Content, post.Comments[0].Content,post.Comments[0].ID, post.Comments[0].Author )
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- 32.
- 33.
运行结果
获得更多内容,关注公众号程序员财富自由之路

公众号:程序员财富自由之路
关注我们,了解更多
边栏推荐
- Redis learning notes - traverse key
- Leetcode topic analysis contains duplicate II
- [GXYCTF2019]BabySQli
- Pizza ordering design - simple factory model
- Cesium加载正射影像方案
- 太阳塔科技招聘PostgreSQL数据库工程师
- Redis learning notes - detailed explanation of redis benchmark
- Redis learning notes - AOF of persistence mechanism
- ionic5表单输入框和单选按钮
- 线性表(LinkList)的链式表示和实现----线性结构
猜你喜欢

A 32KB cache with direct mapping Memory exercises after class
Redis learning notes - AOF of persistence mechanism

UEFI learning 3.6 - ACPI table on ARM QEMU
![[SUCTF 2019]CheckIn](/img/0e/75bb14e7a3e55ddc5126581a663bfb.png)
[SUCTF 2019]CheckIn

Map接口的注意事项
Redis learning notes - redis and Lua
![[geek Challenge 2019] hardsql](/img/73/ebfb410296b8e950c9ac0cf00adc17.png)
[geek Challenge 2019] hardsql

ICLR 2022 | 视频中的动态卷积TAdaConv以及高效的卷积视频理解模型TAdaConvNeXt

Bioinformatics | 基于相互作用神经网络的有效药物-靶标关联预测
![[wangdingbei 2020 Qinglong formation]areuserialz](/img/38/b67f7a42abec1cdaad02f2b7df6546.png)
[wangdingbei 2020 Qinglong formation]areuserialz
随机推荐
Notes on using the coding code base
[GXYCTF2019]BabyUpload
swagger UI :%E2%80%8B
文件的打开新建与存储
[GXYCTF2019]BabyUpload
16. system startup process
什么是闭包函数
Jog运动模式
Redis学习笔记—持久化机制之RDB
web--信息泄漏
多线程习题
Three methods to find the limit of univariate function -- lobida's rule and Taylor's formula
Wechat applet: click the button to switch frequently, overlap the custom markers, but the value does not change
Leetcode topic analysis contains duplicate II
UEFI 学习3.6 - ARM QEMU上的ACPI表
Redis learning notes - redis cli explanation
什么是BFC?BFC可以解决什么问题
mysql乐观锁与悲观锁
Gesture recognition based on mediapipe
One of the 12 balls is different from the others. Provide a balance and find it three times