struct convert json

package main

import (
    "encoding/json"
    "fmt"
)

func main() {
    // 2、初始化结构体
    s := Student{
        Id:      1,
        Name:    "zhangpeng",
        Address: "shenzhen",
        Age:     24,
    }
    //fmt.Printf("%T %#v", s, s)
    //s1, _ := json.Marshal(s)
    //fmt.Println(string(s1))
    //fmt.Println("从这里开始是内存地址", s1)

    // 3、讲结构体转化为json
    sByte, err := json.Marshal(s)
    if err != nil {
        fmt.Println("json.Marshal err,", err)
    }
    fmt.Println("这是json格式:", string(sByte))
    fmt.Println("byte类型数据:", sByte)
}

// 1、定义结构体
type Student struct {
    Id      int
    Name    string
    Address string
    Age     int
}

C:\Users\Administrator\AppData\Local\Temp\GoLand\___go_build_struct_json_go.exe
这是json格式: {"Id":1,"Name":"zhangpeng","Address":"shenzhen","Age":24}
byte类型数据: [123 34 73 100 34 58 49 44 34 78 97 109 101 34 58 34 122 104 97 110 1 50 52 125]

Process finished with the exit code 0

json convert struct

package main

import (
    "encoding/json"
    "fmt"
)

// 1、定义结构体
type Student2 struct {
    Id      int
    Name    string
    Address string
    Age     int
}

func main() {
    // 2、将json字符串转换成结构团体
    var jS = `{"Id":1,"Name":"zhangpeng","Address":"shenzhen","Age":24}`

    // 初始化结构体
    var s Student2

    // 将string类型的数据转换为一个[]byte类型数据
    byteS := []byte(jS)

    // err := json.Unmarshal([]byte(jS), &s)
    err := json.Unmarshal(byteS, &s)
    if err != nil {
        fmt.Printf("Unmarshal err%v\n", err)
    }
    fmt.Println(s.Id, s.Name, s.Address, s.Age)
    fmt.Println(s)
}



1 zhangpeng shenzhen 24
{1 zhangpeng shenzhen 24}

Process finished with the exit code 0