golang 结构体与json

结构体可见性

如果一个Go语言中定义的标识符是首字母大写的,那么对外可见

1
2
3
4
5
type Miners struct {
WorkerName string //首字母大写
Cgminer string
Pool string
}

结构体与JSON

JSON一种轻量级的数据交换格式,易于阅读,通过使用前后端分离项目。利用API获取数据并解析,主要用于数据交互。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package main

import (
"encoding/json"
"fmt"
)

type Book struct {
Name string //字段名必须是大写否则不可见 定制化展示tag `json:"student_id"`
Sn string

}

func main(){

t := Book{"百世go","SN2323232323232323"}

//json 序列化数据

data,err:=json.Marshal(t)

if err != nil{
fmt.Printf("json 格式化错误,err:%v\n",err)
return
}

fmt.Println(string(data))
}

格式输出:

1
{"Name":"百世go","Sn":"SN2323232323232323"}

Make10条数据并且以array格式输出

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package main

import (
"encoding/json"
"fmt"
)

type Book struct {
Name string
Sn string

}

//book的构造函数

func NewBook(name,sn string) Book{
return Book{
Name:name,
Sn:sn,
}
}


func main(){

book_list := make([]Book,0,20) //make一个slice序列
for i:=0;i<10;i++{

b1:=NewBook(fmt.Sprintf("django%v",i),fmt.Sprintf("232344422%v",i))
book_list = append(book_list,b1)
}

//json 序列化数据

data,err:=json.Marshal(book_list)

if err != nil{
fmt.Printf("json 格式化错误,err:%v\n",err)
return
}

fmt.Println(string(data))
}
1
[{"Name":"django0","Sn":"2323444220"},{"Name":"django1","Sn":"2323444221"},{"Name":"django2","Sn":"2323444222"},{"Name":"django3","Sn":"2323444223"},{"Name":"django4","Sn":"2323444224"},{"Name":"django5","Sn":"2323444225"},{"Name":"django6","Sn":"2323444226"},{"Name":"django7","Sn":"2323444227"},{"Name":"django8","Sn":"2323444228"},{"Name":"django9","Sn":"2323444229"}]

反序列成JSON

使用json.Unmarshal

1
2
3
4
5
6
7
8
9
10
11
//json反序列化

Jsostr := `{"Name":"百世go","Sn":"SN2323232323232323"}`
var c2 Book
err =json.Unmarshal([]byte(Jsostr),&c2)
if err != nil{
fmt.Printf("json 解析失败 err:%v\n",err)
return
}

fmt.Println(c2)