encoding/json
encoding/jsonMarshal()Unmarshal()Marshal()Unmarshal()
package main
import (
"encoding/json"
"fmt"
)
type User struct {
Name string `json:"name"`
Age  int    `json:"age"`
}
func main() {
// 将Go语言中的结构体转换为JSON字符串
user := User{Name: "Tom", Age: 18}
jsonData, err := json.Marshal(user)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(jsonData))
// 将JSON字符串转换为Go语言中的结构体
var newUser User
err = json.Unmarshal(jsonData, &newUser)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(newUser.Name, newUser.Age)
}
Marshal()Unmarshal()encoding/json
json.NewEncoder()json.NewDecoder()json.RawMessagejson.Number
encoding/json