package main
import (
"fmt"
"encoding/json"
"log"
)
type Student struct {
Name string `json:"student_name"`
Age int `json:"student_age"`
Sex string `json:"student_sex"`
Handle bool `json:"is_handle,omitempty"`
Habbits []string `json:"student_habbits"`
}
var students = []Student{
{Name:"Marco", Age:19, Sex:"男", Handle:false, Habbits:[]string{"music","program","write"}},
{Name:"Mike", Age:20, Sex:"男", Handle:true,Habbits:[]string{"basketball","chess","sing"}},
{Name:"Lisa", Age:19, Sex:"女", Habbits:[]string{"art","sing","marco"}},
}
func main() {
//生成json格式
data, err := json.MarshalIndent(students,""," ")
if err != nil {
log.Fatal("json Marshaling failed: %s",err)
}
fmt.Printf("%s\n",data)
//反json序列化
var get []Student
if err := json.Unmarshal(data,&get); err != nil {
log.Fatalf("json Unmarshal failed: %s\n",err)
}
for _, student := range get {
fmt.Printf("Name: %s\n",student.Name)
fmt.Printf("Age: %d\n",student.Age)
fmt.Printf("Sex: %s\n",student.Sex)
fmt.Printf("Handle: %t\n",student.Handle)
fmt.Printf("Habbits:")
for _, habbit := range student.Habbits {
fmt.Printf("\t%s",habbit)
}
fmt.Printf("\n-------------------------------------------\n")
}
fmt.Println()
}
Go Json序列化和反序列化
最新推荐文章于 2024-09-23 16:59:20 发布