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()
}
版权声明:本文为RGBMarco原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。