package main
import (
"encoding/json"
"fmt"
)
//1.结构体与JSON序列化
//JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。
type Student struct {
ID int
Gender string
Name string//需要大写,私有不能被json包访问
}
//Class 班级
type Class struct {
Title string
Students []*Student
}
func test() {
c := &Class{
Title: "101",
Students: make([]*Student, 0, 200),
}
for i := 0; i < 10; i++ {
stu := &Student{
ID: i,
Name: fmt.Sprintln("stu%d", i), //Sprintln输出字符串
Gender: "男",
}
c.Students = append(c.Students, stu)
}
//JSON序列化
data, err := json.Marshal(c) //编码成JSON字符串
if err != nil {
fmt.Println("json marshal failed")
return
}
fmt.Printf("json:%s\n", data)
//JSON反序列化:JSON格式的字符串-->结构体
str := `{"Title":"101","Students":[{"ID":0,"Gender":"男","Name":"stu00"},{"ID":1,"Gender":"男","Name":"stu01"},{"ID":2,"Gender":"男","Name":"stu02"},{"ID":3,"Gender":"男","Name":"stu03"},{"ID":4,"Gender":"男","Name":"stu04"},{"ID":5,"Gender":"男","Name":"stu05"},{"ID":6,"Gender":"男","Name":"stu06"},{"ID":7,"Gender":"男","Name":"stu07"},{"ID":8,"Gender":"男","Name":"stu08"},{"ID":9,"Gender":"男","Name":"stu09"}]}`
c1 := &Class{}
err = json.Unmarshal([]byte(str), c1)//要将json数据解码写入一个接口类型值
if err != nil {
fmt.Println("json unmarshal failed!")
return
}
fmt.Printf("%#v\n", c1)
}
//2.Tag->`key1:"value1" key2:"value2"`
type Student1 struct {
ID int `json:"id"` //通过指定tag实现json序列化该字段时的key
Gender string //json序列化是默认使用字段名作为key
name string //私有不能被json包访问
}
func test1() {
s1 := Student1{
ID: 1,
Gender: "女",
name: "pprof",
}
data, err := json.Marshal(s1)
if err != nil {
fmt.Println("json marshal failed!")
return
}
fmt.Printf("json str:%s\n", data) //json str:{"id":1,"Gender":"女"}//改变键值
}
func main(){
test()
test1()
}
Go结构体进阶2
最新推荐文章于 2024-08-21 16:39:46 发布