耐心和持久胜过激烈和狂热。
哈喽大家好,我是陈明勇,今天分享的内容是 Go 结构体 与 JSON 之间的转换。如果本文对你有帮助,不妨点个赞,如果你是 Go 语言初学者,不妨点个关注,一起成长一起进步,如果本文有错误的地方,欢迎指出!
前言JSONJSONJSONJSON
结构体转 JSON
Marshal(v any) ([]byte, error)vJSON[]byte
import (
"encoding/json"
"fmt"
)
type User struct {
Name string
Age int
Height float64
Weight *float64
Child bool
marriageStatus string
}
func main() {
weight := 120.5
user := User{
Name: "gopher",
Age: 18,
Height: 180.5,
Weight: &weight,
Child: false,
marriageStatus: "未婚",
}
jsonBytes, err := json.Marshal(user)
if err != nil {
fmt.Println("error: ", err)
return
}
fmt.Println(string(jsonBytes)) // {"Name":"gopher","Age":18,"Height":180.5,"Weight":120.5,"Child":false}
}
{"Name":"gopher","Age":18,"Height":180.5,"Weight":120.5,"Child":false}
JSONkeyGo
JSON
import (
"encoding/json"
"fmt"
)
type User struct {
Name string `json:"name"`
Age int `json:"age"`
Height float64 `json:"height"`
Weight *float64 `json:"weight"`
Child bool `json:"child"`
MarriageStatus string `json:"-"`
}
func main() {
weight := 120.5
user := User{
Name: "gopher",
Age: 18,
Height: 180.5,
Weight: &weight,
Child: false,
MarriageStatus: "未婚",
}
jsonBytes, err := json.Marshal(user)
if err != nil {
fmt.Println("error: ", err)
return
}
fmt.Println(string(jsonBytes)) // {"name":"gopher","age":18,"height":180.5,"weight":120.5,"child":false}
}
JSONJSONJSON-JSON
JSON 解析结构体
Unmarshal(data []byte, v any) errorJSON
import (
"encoding/json"
"fmt"
)
type User struct {
Name string `json:"name"`
Age int `json:"age"`
Height float64 `json:"height"`
Child bool `json:"-"`
marriageStatus string
}
func main() {
userStr := `
{
"name": "gopher",
"age": 18,
"height": 180.5,
"child": true,
"marriageStatus": "未婚"
}
`
user := &User{}
err := json.Unmarshal([]byte(userStr), &user)
if err != nil {
fmt.Println("error: ", err)
return
}
fmt.Printf("%#v", user) // &main.User{Name:"gopher", Age:18, Height:180.5, Child:false, marriageStatus:""}
}
&main.User{Name:"gopher", Age:18, Height:180.5, Child:false, marriageStatus:""}
UnmarshalJSONJSONkeyJSONkeyvalueJSONkeyJSON-
小结
GoJSONJSONkeyJSON-JSONJSON