JSON(JavaScript Object Notation)是一种轻量级的数据交换格式。易于人阅读和编写。同时也易于机器解析和生成。JSON键值对是用来保存JS对象的一种方式,键/值对组合中的键名写在前面并用双引号""包裹,使用冒号:分隔,然后紧接着值;多个键值之间使用英文,分隔。
{“Name”:“stu_0”,“Score”:1},{“Name”:“stu_1”,“Score”:11},{“Name”:“stu_2”,“Score”:21}
JSON序列化的注意要点
- 请注意结构体中的成员变量如果要转为JSON格式的,一定要大写,大写代表着可以被其他类调用
- 大写代表public 小写是私有
type Student struct {
Name string //请注意结构体中的成员变量如果要转为JSON格式的,一定要大写,大写代表着可以被其他类调用
//大写代表public 小写是私有
Score int
}
结果
代码
package main
import (
"encoding/json"
"fmt"
"strconv"
)
//学生类
type Student struct {
Name string //请注意结构体中的成员变量如果要转为JSON格式的,一定要大写,大写代表着可以被其他类调用
//大写代表public 小写是私有
Score int
}
//班级类
type Class struct {
Id int
Students []*Student //继承于Student
}
func main() {
/*
结构体与json格式的相互转换
*/
//一个班级有三个学生
var myClass = &Class{
Id: 5,
Students: make([]*Student, 0, 200),
}
//创建3个学生
for i := 0; i < 3; i++ {
myStudents := &Student{
Name: "stu_" + strconv.Itoa(i),
Score: i*10 + 1,
}
fmt.Println(myStudents.Name)
myClass.Students = append(myClass.Students, myStudents)
}
fmt.Println(myClass.Students) //打印出是地址
//JSON序列化:结构体-->JSON格式的字符串
data, err := json.Marshal(myClass)
if err != nil {
fmt.Println("json marshal failed")
return
}
fmt.Printf("json:%s\n", data)
//JSON反序列化:JSON格式的字符串-->结构体
str := `{"Id":5,"Students":[{"Name":"stu_0","Score":1},{"Name":"stu_1","Score":11},{"Name":"stu_2","Score":21}]}`
c1 := &Class{} //转换出来后存放的地方
err = json.Unmarshal([]byte(str), c1)
if err != nil {
fmt.Println("json unmarshal failed!")
return
}
fmt.Printf("%#v\n", c1)
}