JSON:
json.Marshal()json.Unmarshal()
创建格式:
基本数据类型序列化:
func testBasic() {
num := 1.111
marshal, err := json.Marshal(num)
if err != nil {
fmt.Println("json.Marshal err:", err)
}
fmt.Println("序列化后:", string(marshal)) // 序列化后: 1.111
}
结构体序列化:
func main() {
testStudent()
}
/**
type Student struct {
Name string
Age int
Birthday string
Address string
}
*/
// 如果加上`json:"student_name"`,序列化以后的数据字段是返回指定格式的,可以小写,json固定,后面的随意
type Student struct {
// 变量首字母大写才能被解析
Name string `json:"student_name"`
Age int `json:"student_age"`
Birthday string `json:"student_birthday"`
Address string `json:"student_address"`
}
func testStudent() {
student := Student{
Name: "itzhuzhu",
Age: 24,
Birthday: "1998-01-01",
Address: "广州市天河区",
}
marshal, err := json.Marshal(&student)
if err != nil {
fmt.Println("json.Marshal err:", err)
}
fmt.Println("序列化后:", string(marshal)) // 序列化后:{"Name":"itzhuzhu","Age":24,"Birthday":"1998-01-01","Address":"广州市天河区"}
}
map序列化:
func testMap() {
var m map[string]interface{}
m = make(map[string]interface{})
m["name"] = "韩信"
m["age"] = 23
m["address"] = "广州"
marshal, err := json.Marshal(m)
if err != nil {
fmt.Println("json.Marshal err:", err)
}
fmt.Println("序列化后:", string(marshal)) // 序列化后: {"address":"广州","age":23,"name":"韩信"}
}
切片序列化:
func testSlice() {
var slice []map[string]interface{}
var m map[string]interface{}
m = make(map[string]interface{})
m["name"] = "韩信"
m["age"] = 23
m["address"] = "广州"
slice = append(slice, m)
marshal, err := json.Marshal(m)
if err != nil {
fmt.Println("json.Marshal err:", err)
}
fmt.Println("序列化后:", string(marshal)) // 序列化后: {"address":"广州","age":23,"name":"韩信"}
}
反序列化为结构体:
func deserialize() {
str := "{\"Name\":\"itzhuzhu\",\"Age\":24,\"Birthday\":\"1998-01-01\",\"Address\":\"广州市天河区\"}"
// 使用Unmarshal反序列化
var student Student
err := json.Unmarshal([]byte(str), &student)
if err != nil {
fmt.Println("json.Unmarshal err:", err)
}
fmt.Println("反序列化后:", student) // 反序列化后: {itzhuzhu 24 1998-01-01 广州市天河区}
}
反序列化为map:
func deserializeMap() {
str := " {\"address\":\"广州\",\"age\":23,\"name\":\"韩信\"}"
// 反序列化的时候不需要make,被封装到Unmarshal中了
var m map[string]interface{}
err := json.Unmarshal([]byte(str), &m)
if err != nil {
fmt.Println("json.Unmarshal err:", err)
}
fmt.Println("反序列化后:", m) // map[address:广州 age:23 name:韩信]
}
反序列化为切片:
func deserializeSlice() {
str := " [{\"address\":\"广州\",\"age\":23,\"name\":\"韩信\"}]"
var slice []map[string]interface{}
err := json.Unmarshal([]byte(str), &slice)
if err != nil {
fmt.Println("json.Unmarshal err:", err)
}
fmt.Println("反序列化后:", slice) // 反序列化后: [map[address:广州 age:23 name:韩信]]
}