import (
"encoding/json"
"fmt"
)
type Student struct {
ID int
Gender string
Name string //私有属性不能被json包访问
Sno string
}
func main() {
var s1 = Student{
ID: 12,
Gender: "男",
Name: "李四",
Sno: "s0001",
}
fmt.Printf("%#v\n", s1) //main.Student{ID:12, Gender:"男", Name:"李四", Sno:"s0001"}
jsonByte, _ := json.Marshal(s1)
jsonStr := string(jsonByte)
fmt.Printf("%v", jsonStr) //{"ID":12,"Gender":"男","Name":"李四","Sno":"s0001"}
}
package main
import (
"encoding/json"
"fmt"
)
type Student struct {
ID int
Gender string
Name string //私有属性不能被json包访问
Sno string
}
func main() {
//json字符串
var str = `{"ID":12,"Gender":"男","Name":"李四","Sno":"s0001"}`
var s1 Student
err := json.Unmarshal([]byte(str), &s1)
if err != nil {
fmt.Println(err)
}
fmt.Printf("%#v\n", s1)
fmt.Println(s1.Name)
}
package main
import (
"encoding/json"
"fmt"
)
//结构体标签
type Student struct {
Id int `json:"id"`
Gender string `json:"gender"`
Name string `json:"name"` //私有属性不能被json包访问
Sno string `json:"sno"`
}
func main() {
var s1 = Student{
Id: 12,
Gender: "男",
Name: "李四",
Sno: "s0001",
}
fmt.Printf("%#v\n", s1) //main.Student{Id:12, Gender:"男", Name:"李四", Sno:"s0001"}
jsonByte, _ := json.Marshal(s1)
jsonStr := string(jsonByte)
fmt.Printf("%v", jsonStr) //{"id":12,"gender":"男","name":"李四","sno":"s0001"}
}
package main
import (
"encoding/json"
"fmt"
)
//Student 学生
type Student struct {
Id int
Gender string
Name string
}
//Class 班级
type Class struct {
Title string
Students []Student
}
func main() {
c := Class{
Title: "001班",
Students: make([]Student, 0),
}
for i := 1; i <= 10; i++ {
s := Student{
Id: i,
Gender: "男",
Name: fmt.Sprintf("stu_%v", i),
}
c.Students = append(c.Students, s)
}
// fmt.Println(c)
strByte, err := json.Marshal(c)
if err != nil {
fmt.Println(err)
} else {
strJson := string(strByte)
fmt.Println(strJson)
}
}
package main
import (
"encoding/json"
"fmt"
)
//Student 学生
type Student struct {
ID int
Gender string
Name string
}
//Class 班级
type Class struct {
Title string
Students []Student
}
func main() {
str := `{"Title":"001班","Students":[{"Id":1,"Gender":"男","Name":"stu_1"},{"Id":2,"Gender":"男","Name":"stu_2"},{"Id":3,"Gender":"男","Name":"stu_3"},{"Id":4,"Gender":"男","Name":"stu_4"},{"Id":5,"Gender":"男","Name":"stu_5"},{"Id":6,"Gender":"男","Name":"stu_6"},{"Id":7,"Gender":"男","Name":"stu_7"},{"Id":8,"Gender":"男","Name":"stu_8"},{"Id":9,"Gender":"男","Name":"stu_9"},{"Id":10,"Gender":"男","Name":"stu_10"}]}`
var c = &Class{}
err := json.Unmarshal([]byte(str), c)
if err != nil {
fmt.Println(err)
} else {
fmt.Printf("%#v\n", c)
fmt.Printf("%v", c.Title)
}
}