This package can realize the encoding and decoding of json, which is to convert the json string to struct
, or struct
convert to json.
The two core functions
Encoding function Marshal
func Marshal(v interface{}) ([]byte, error)
Encode struct or map into json, which can receive any type
Convert structure to json
package main
import (
"encoding/json"
"fmt")
type Person struct {
Name string
Age int
Email string
}
func Marsha() {
p := Person{
Name: "tom",
Age: 20,
Email: "[email protected]",
}
b, _ := json.Marshal(p)
fmt.Printf("b: %v\n", string(b))
}
func main() {
Marsha()
}
map converted to json
package main
import (
"encoding/json"
"fmt")
type Person struct {
Name string
Age int
Email string
}
func Marsha() {
p := make(map[string]interface{}, 20)
p["名称"] = "张三"
p["性别"] = "男"
p["年龄"] = "18"
b, _ := json.Marshal(p)
fmt.Printf("b: %v\n", string(b))
}
func main() {
Marsha()
}
Decoding function Unmarshal
func Unmarshal(data []byte, v interface{}) error
Transcode json into struct structure or map
The key point of this function is the data type of v, but it is recommended to use the structure as the type of v. After all, you can use the tag tag to analyze the data more accurately. Special attention: the second parameter must be passed in the address, otherwise the modification will not succeed
json to map
package main
import (
"encoding/json"
"fmt")
type Person struct {
Name string
Age int
Email string
}
func Marsha() []byte {
p := make(map[string]interface{}, 20)
p["名称"] = "张三"
p["性别"] = "男"
p["年龄"] = "18"
b, _ := json.Marshal(p)
return b
}
func Unmarshal(b []byte) {
var m map[string]interface{}
json.Unmarshal(b, &m)
fmt.Printf("%v\n", m)
}
func main() {
Unmarshal(Marsha())
}
Convert json to structure
package main
import (
"encoding/json"
"fmt"
)
type Person struct {
Name string
Age int
Gender string
}
func Marsha() []byte {
p := make(map[string]interface{}, 20)
p["name"] = "张三"
p["gender"] = "男"
p["age"] = "18"
b, _ := json.Marshal(p)
return b
}
func Unmarshal(b []byte) {
var m Person
json.Unmarshal(b, &m)
fmt.Printf("%v\n", m)
}
func main() {
Unmarshal(Marsha())
}
parse nested types
package main
import (
"encoding/json"
"fmt"
)
type Parents []string
type Person struct {
Name string
Age int
Email string
Parents
}
// 解析嵌套类型
func Unmarshal() {
b := []byte(`{"Name":"tom","Age":20,"Email":"[email protected]", "Parents":["tom", "kite"]}`)
var f Person
json.Unmarshal(b, &f)
fmt.Printf("f: %v\n", f)
}
func main() {
Unmarshal()
}
ignore field
If you want to encode/decode in json (serialize or deserialize) to ignore a field in the structure, you can add it to the tag as follows -
.
If you want to ignore a field in the structure during json serialization/deserialization, you can add it to the tag as follows -
.
Of course, if you make the variable name into lowercase, you can also achieve the effect of ignoring it. §(  ̄▽ ̄ )§
// 使用json tag指定json序列化与反序列化时的行为
type Person struct {
Name string `json:"name"` // 指定json序列化/反序列化时使用小写name
Age int64
Weight float64 `json:"-"` // 指定json序列化/反序列化时忽略此字段
}
Ignore empty fields
When the fields in the struct have no value, json.Marshal()
these fields will not be ignored during serialization, but the type zero value of the default output field (for example, the int
type float
zero value is 0, string
the type zero value is ""
, and the object type zero value is nil). If you want to ignore these fields without values during serialization, you can add omitempty
tags to the corresponding fields.
for example:
type User struct {
Name string `json:"name"`
Email string `json:"email"`
Hobby []string `json:"hobby"`
}
func omitemptyDemo() {
u1 := User{
Name: "七米",
}
// struct -> json string
b, err := json.Marshal(u1)
if err != nil {
fmt.Printf("json.Marshal failed, err:%v\n", err)
return
}
fmt.Printf("str:%s\n", b)
}
Output result:
str:{"name":"七米","email":"","hobby":null}
If you want to remove null fields in the final serialization result, you can define a structure like this:
// 在tag中添加omitempty忽略空值
// 注意这里 hobby,omitempty 合起来是json tag值,中间用英文逗号分隔
type User struct {
Name string `json:"name"`
Email string `json:"email,omitempty"`
Hobby []string `json:"hobby,omitempty"`
}
At this point, execute the above again omitemptyDemo
, the output result is as follows:
str:{"name":"七米"} // 序列化结果中没有email和hobby字段
Ignore empty fields of nested structures
Let's first look at several examples of structure nesting:
type User struct {
Name string `json:"name"`
Email string `json:"email,omitempty"`
Hobby []string `json:"hobby,omitempty"`
Profile
}
type Profile struct {
Website string `json:"site"`
Slogan string `json:"slogan"`
}
func nestedStructDemo() {
u1 := User{
Name: "七米",
Hobby: []string{"足球", "双色球"},
}
b, err := json.Marshal(u1)
if err != nil {
fmt.Printf("json.Marshal failed, err:%v\n", err)
return
}
fmt.Printf("str:%s\n", b)
}
Profile
The serialized json string in anonymous nesting is single-layer:
str:{"name":"七米","hobby":["足球","双色球"],"site":"","slogan":""}
If you want to turn it into a nested json string, you need to change it to a named nest or define a field tag:
type User struct {
Name string `json:"name"`
Email string `json:"email,omitempty"`
Hobby []string `json:"hobby,omitempty"`
Profile `json:"profile"`
}
// str:{"name":"七米","hobby":["足球","双色球"],"profile":{"site":"","slogan":""}}
To ignore the field when the nested structure is empty, adding omitempty
is not enough:
type User struct {
Name string `json:"name"`
Email string `json:"email,omitempty"`
Hobby []string `json:"hobby,omitempty"`
Profile `json:"profile,omitempty"`
}
// str:{"name":"七米","hobby":["足球","双色球"],"profile":{"site":"","slogan":""}}
You also need to use nested struct pointers:
type User struct {
Name string `json:"name"`
Email string `json:"email,omitempty"`
Hobby []string `json:"hobby,omitempty"`
*Profile `json:"profile,omitempty"`
}
// str:{"name":"七米","hobby":["足球","双色球"]}
Do not modify the original structure and ignore null value fields
We need json serialization User
, but we don’t want to serialize the password , and we don’t want to modify User
the structure . At this time, we can create another structure PublicUser
anonymous nested source User
, specify Password
the field as an anonymous structure pointer type, and add omitempty
a tag. The sample code is as follows:
type User struct {
Name string `json:"name"`
Password string `json:"password"`
}
type PublicUser struct {
*User // 匿名嵌套
Password *struct{} `json:"password,omitempty"`
}
func omitPasswordDemo() {
u1 := User{
Name: "七米",
Password: "123456",
}
b, err := json.Marshal(PublicUser{User: &u1})
if err != nil {
fmt.Printf("json.Marshal u1 failed, err:%v\n", err)
return
}
fmt.Printf("str:%s\n", b) // str:{"name":"七米"}
}