Go语言JSON 处理

简介: Go语言JSON 处理

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)
}


解析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)


运行结果


=== RUN   TestJsonMash
======================
{[{Elinx 26 0001-01-01 00:00:00 +0000 UTC []} {Twinkle 21 0001-01-01 00:00:00 +0000 UTC []}]}
{"Persons":[{"Name":"Elinx","Age":26,"Birth":"0001-01-01T00:00:00Z","Children":null}
--- PASS: TestJsonMash (0.00s)
PASS


使用 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))
}


运行结果:


=== RUN   TestJsonMash1
{
 "ID": 2,
 "content": "Hello World",
 "author": "userB",
 "label": [
  "linux",
  "shell"
 ]
}
--- PASS: TestJsonMash1 (0.00s)
PASS


如何使用 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"
        }
    ]
}


测试代码


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 )
}


运行结果


=== RUN   TestJsonStruct
{1 hello world {2 userA} true [] <nil> [0xc00016d1a0 0xc00016d1d0]}
{2 userA} hello world good post1 3 userB
--- PASS: TestJsonStruct (0.00s)
PASS
相关文章
|
1月前
|
存储 安全 Java
【Golang】(4)Go里面的指针如何?函数与方法怎么不一样?带你了解Go不同于其他高级语言的语法
结构体可以存储一组不同类型的数据,是一种符合类型。Go抛弃了类与继承,同时也抛弃了构造方法,刻意弱化了面向对象的功能,Go并非是一个传统OOP的语言,但是Go依旧有着OOP的影子,通过结构体和方法也可以模拟出一个类。
152 1
|
3月前
|
Cloud Native 安全 Java
Go:为云原生而生的高效语言
Go:为云原生而生的高效语言
286 1
|
9月前
|
编译器 Go
揭秘 Go 语言中空结构体的强大用法
Go 语言中的空结构体 `struct{}` 不包含任何字段,不占用内存空间。它在实际编程中有多种典型用法:1) 结合 map 实现集合(set)类型;2) 与 channel 搭配用于信号通知;3) 申请超大容量的 Slice 和 Array 以节省内存;4) 作为接口实现时明确表示不关注值。此外,需要注意的是,空结构体作为字段时可能会因内存对齐原因占用额外空间。建议将空结构体放在外层结构体的第一个字段以优化内存使用。
|
9月前
|
运维 监控 算法
监控局域网其他电脑:Go 语言迪杰斯特拉算法的高效应用
在信息化时代,监控局域网成为网络管理与安全防护的关键需求。本文探讨了迪杰斯特拉(Dijkstra)算法在监控局域网中的应用,通过计算最短路径优化数据传输和故障检测。文中提供了使用Go语言实现的代码例程,展示了如何高效地进行网络监控,确保局域网的稳定运行和数据安全。迪杰斯特拉算法能减少传输延迟和带宽消耗,及时发现并处理网络故障,适用于复杂网络环境下的管理和维护。
|
3月前
|
Cloud Native Go API
Go:为云原生而生的高效语言
Go:为云原生而生的高效语言
359 0
|
3月前
|
Cloud Native Java Go
Go:为云原生而生的高效语言
Go:为云原生而生的高效语言
232 0
|
3月前
|
Cloud Native Java 中间件
Go:为云原生而生的高效语言
Go:为云原生而生的高效语言
212 0
|
3月前
|
Cloud Native Java Go
Go:为云原生而生的高效语言
Go:为云原生而生的高效语言
305 0
|
3月前
|
数据采集 Go API
Go语言实战案例:多协程并发下载网页内容
本文是《Go语言100个实战案例 · 网络与并发篇》第6篇,讲解如何使用 Goroutine 和 Channel 实现多协程并发抓取网页内容,提升网络请求效率。通过实战掌握高并发编程技巧,构建爬虫、内容聚合器等工具,涵盖 WaitGroup、超时控制、错误处理等核心知识点。
|
3月前
|
数据采集 JSON Go
Go语言实战案例:实现HTTP客户端请求并解析响应
本文是 Go 网络与并发实战系列的第 2 篇,详细介绍如何使用 Go 构建 HTTP 客户端,涵盖请求发送、响应解析、错误处理、Header 与 Body 提取等流程,并通过实战代码演示如何并发请求多个 URL,适合希望掌握 Go 网络编程基础的开发者。
下一篇
oss云网关配置