Go 結構體 JSON 序列化 反序列化


先定義一對嵌套的結構體

//Student 學生
type Student struct {
    ID     int              `json:"id"`              //  "ID"首字母大寫是因為要序列化,必須大寫,json包里才能訪問。  `json:"id"`是讓序列化后,"ID"用小寫表示
    Gender string    `json:"gender"`
    Name   string    `json:"name"`
}

//Class 班級
type Class struct {
    Title    string                `json:"title"`
    Students []*Student    `json:"students"`
}

 

序列化和反序列化

package main

import (
     "encoding/json"
    "fmt"
)

func jsonSerialize(c *Class) string {
    // 對Class 序列化
    data, err :=  json.Marshal(c)        //序列化,返回data為bytes類型
    if err != nil {
        fmt.Println("Class序列化失敗")
        return ""
    }
    return  fmt.Sprintf("%s", data)
}

func jsonDeserialize(s string) *Class {
    // 對Class 反序列化
     c1 := Class{}
    err :=  json.Unmarshal([]byte(s),  &c1)       //傳指針是為了能在json包里修改p2的值
    if err != nil {
        fmt.Println("Class反序列化失敗")
        return nil
    }
    return  &c1
}

func main() {
    c := &Class{
        Title:    "101",
        Students: make([]*Student, 0, 200),
    }
    for i := 0; i < 10; i++ {
        stu := &Student{
            Name:   fmt.Sprintf("stu%02d", i),
            Gender: "男",
            ID:     i,
        }
        c.Students = append(c.Students, stu)
    }
    // JSON序列化  c為內存地址
    fmt.Println(jsonSerialize(c))

    //JSON反序列化
    str := `{"Title":"101","Students":[{"ID":0,"Gender":"男","Name":"stu00"},{"ID":1,"Gender":"男","Name":"stu01"},{"ID":2,"Gender":"男","Name":"stu02"}]}`
    c1 := jsonDeserialize(str)
    fmt.Println(c1.Students[0])
    fmt.Printf("%#v\n", c1)
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM