golang中内置encoding包的各个子包,提供了各种数据与编码、文本格式之间转换的方法
//将对象v序列化为json格式,并返回byte切片
func Marshal(v any) ([]byte, error)
//将对象v序列化为json格式,并返回byte切片,prefix为前缀,indent为缩进
func MarshalIndent(v any, prefix, indent string) ([]byte, error)
//将json字符串的byte切片反序列化到对象v中
func Unmarshal(data [] byte, v any) error
package main
import (
"encoding/json"
"fmt"
)
type Stu struct {
Id string `json:"id"`
Name string `json:"name"`
Age int `json:"age"`
}
func main() {
s1 := Stu{"s1", "lucy", 18}
s2 := Stu{"s2", "tom", 20}
data := []Stu{s1, s2}
b, err := json.Marshal(data)
if err != nil {
fmt.Println(err)
}
fmt.Println(string(b))
//[{"id":"s1","name":"lucy","age":18},{"id":"s2","name":"tom","age":20}]
}
package main
import (
"encoding/json"
"fmt"
)
type Stu struct {
Id string `json:"id"`
Name string `json:"name"`
Age int `json:"age"`
}
func main() {
j := `[{"id":"s1","name":"lucy","age":18},{"id":"s2","name":"tom","age":20}]`
var data []Stu
err := json.Unmarshal([]byte(j), &data)
if err != nil {
fmt.Println(err)
}
fmt.Println(data) //[{s1 lucy 18} {s2 tom 20}]
}
除了 marshal 和 unmarshal 函数,Go 还提供了 Decoder 和 Encoder 对 stream JSON 进行处理,常见 request 中的 Body、文件等。
package main
import (
"encoding/json"
"fmt"
"os"
)
type Stu struct {
Id string `json:"id"`
Name string `json:"name"`
Age int `json:"age"`
}
func main() {
s1 := Stu{"s1", "lucy", 18}
s2 := Stu{"s2", "tom", 20}
data := []Stu{s1, s2}
f, err := os.OpenFile("./stu.json", os.O_WRONLY|os.O_CREATE, 0777)
if err != nil {
fmt.Println(err)
}
defer f.Close()
encoder := json.NewEncoder(f)
err = encoder.Encode(data)
if err != nil {
fmt.Println(err)
}
}
package main
import (
"encoding/json"
"fmt"
"os"
)
type Stu struct {
Id string `json:"id"`
Name string `json:"name"`
Age int `json:"age"`
}
func main() {
var data []Stu
f, err := os.Open("./stu.json")
if err != nil {
fmt.Println(err)
}
defer f.Close()
decoder := json.NewDecoder(f)
err = decoder.Decode(&data)
if err != nil {
fmt.Println(err)
}
fmt.Println(data) //[{s1 lucy 18} {s2 tom 20}]
}