omitempty
忽略 struct 空字段,当字段的值为空值的时候,它不会出现在JSON数据中.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
package main
import (
"encoding/json"
"fmt"
)
type User struct {
Email string `json:"email"`
Password string `json:"password,omitempty"`
}
func main() {
jsonByte, _ := json.Marshal(User{Email: "7@qq.com"})
fmt.Println(string(jsonByte))
}
// 输出结果
// 不带 omitempty 的输出结果:{"email":"7@qq.com","password":""}
// 带 omitempty 的输出结果:{"email":"7@qq.com"}
|
临时合并两个struct
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
|
package main
import (
"encoding/json"
"fmt"
)
func main() {
type BlogPost struct {
URL string `json:"url"`
Title string `json:"title"`
}
type Analytics struct {
Visitors int `json:"visitors"`
PageViews int `json:"page_views"`
}
blog := BlogPost{URL: "http://www.x.com", Title: "title"}
analytics := Analytics{Visitors: 100, PageViews: 200}
jsonByte, _ := json.Marshal(struct {
*BlogPost
*Analytics
}{&blog, &analytics})
fmt.Println(string(jsonByte))
// 输出结果
// {"url":"http://www.x.com","title":"title","visitors":100,"page_views":200}
}
|
一个json切分成两个struct
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
34
|
package main
import (
"encoding/json"
"fmt"
)
func main() {
type BlogPost struct {
URL string `json:"url"`
Title string `json:"title"`
}
type Analytics struct {
Visitors int `json:"visitors"`
PageViews int `json:"page_views"`
}
var (
blog BlogPost
analytics Analytics
)
json.Unmarshal([]byte(`{"url":"http://www.x.com","title":"title","visitors":100,"page_views":200}`), &struct {
*BlogPost
*Analytics
}{&blog, &analytics})
fmt.Println(blog)
fmt.Println(analytics)
// 输出结果
// {http://www.x.com title}
// {100 200}
}
|
数字以字符串形式输出
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
package main
import (
"encoding/json"
"fmt"
)
type Test struct {
Email string `json:"email"`
Field int `json:"field,string"`
}
func main() {
jsonByte, _ := json.Marshal(Test{Email: "7@qq.com", Field: 100})
fmt.Println(string(jsonByte))
}
// 输出结果
// {"email":"7@qq.com","field":"100"}
|
json和map转换
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
func main() {
jsonStr := `
{
"env": "local",
"redis_address": "127.0.0.1:6379",
"redis_password": "xxx"
}
`
// json转换成map
m := make(map[string]interface{})
_ = json.Unmarshal([]byte(jsonStr), &m)
fmt.Println(m) // 输出:map[env:local redis_address:127.0.0.1:6379 redis_password:xxx]
// map转换成json
j, _ := json.Marshal(m)
fmt.Println(string(j)) // 输出:{"env":"local","redis_address":"127.0.0.1:6379","redis_password":"xxx"}
}
|