Go Json序列化和反序列化

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()
}

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值