golang 结构体

结构体与JSON序列化

  JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。易于人阅读和编写。同时也易于机器解析和生成。JSON键值对是用来保存JS对象的一种方式,键/值对组合中的键名写在前面并用双引号""包裹,使用冒号:分隔,然后紧接着值;多个键值之间使用英文,分隔。

package main

import (
    "encoding/json"
    "fmt"
)

type Student struct {
    Id     int
    Gender string
    Name   string
}

type Class struct {
    Title    string
    Students []*Student
}

func main() {
    c := &Class{
        Title:    "101",
        Students: make([]*Student, 0, 200),
    }

    for i := 0; i < 10; i++ {
        stu := &Student{
            Id:     i,
            Gender: "",
            Name:   fmt.Sprintf("stu%02d", i),
        }
        c.Students = append(c.Students, stu)
    }
    fmt.Printf("c: %v\n", c)

    data, err := json.Marshal(c)
    if err != nil {
        fmt.Println("json marsharl failed")
        return
    }

    fmt.Printf("json:%s\n", data)
    var class Class
    _ = json.Unmarshal(data, &class)
    fmt.Printf("class: %v\n", class)
    fmt.Printf("class.Students: %v\n", *(class.Students)[0])     //{0 男 stu00}
    fmt.Printf("class.Students: %v\n", class.Students[0])        //&{0 男 stu00}
    fmt.Printf("class.Students: %v\n", class.Students[0].Name)   //stu00
    fmt.Printf("class.Students: %v\n", class.Students[0].Gender) //
    fmt.Printf("class.Students: %v\n", class.Students[0].Id)     //0
}

 结果如下:

c: &{101 [0xc0000764b0 0xc0000764e0 0xc000076510 0xc000076540 0xc000076570 0xc0000765a0 0xc0000765d0 0xc000076600 0xc000076630 0xc000076660]}
json:{"Title":"101","Students":[{"Id":0,"Gender":"","Name":"stu00"},{"Id":1,"Gender":"","Name":"stu01"},{"Id":2,"Gender":"","Name":"stu02"},{"Id":3,"Gender":"","Name":"stu03"},{"Id":4,"Gender":"","Name":"stu04"},{"Id":5,"Gender":"","Name":"stu05"},{"Id":6,"Gender":"","Name":"stu06"},{"Id":7,"Gender":"","Name":"stu07"},{"Id":8,"Gender":"","Name":"stu08"},{"Id":9,"Gender":"","Name":"stu09"}]}
class: {101 [0xc0000769f0 0xc000076a20 0xc000076a50 0xc000076a80 0xc000076ae0 0xc000076b10 0xc000076b40 0xc000076b70 0xc000076ba0 0xc000076bd0]}
class.Students: {0 男 stu00}
class.Students: &{0 男 stu00}
class.Students: stu00
class.Students: 男
class.Students: 0

 

posted @ 2023-01-16 17:57  wushaoyu  阅读(15)  评论(0编辑  收藏  举报