在网络数据传输,经常需要把要发送和接收的结构体信息序列化成特定的格式传输,json是其中比较常用和简洁的一种协议。在go语言中encoding/json包里有对应的api接口可以支持,具体使用参见下面例子:
package main
import (
"fmt"
"encoding/json"
)
//注意:需要序列化的每个结构体中成员,首字母必须要大写,否则序列化后的数据是空!
type Worker struct {
Id int
Name string
Pay float64
}
type Office struct {
Area int
Build int
}
type Company struct {
Worker
Office
Credit int
}
func main() {
//初始化一个原始结构体对象
encdata:=Company{Worker{Name:"李三",Pay:8050.1},Office{Build:1},1001}
//用json序列化
jsondata,err:=json.Marshal(&encdata)
if err!=nil {
fmt.Println(err)
} else {
//json数据和网络、文件等都是[]byte格式([]uint8),所以需要转换成string
fmt.Printf("json序列化成功(格式:%T),内容:%s\n",jsondata,string(jsondata))
}
workercre:=struct {//定义的一个匿名结构体
Worker
Credit int
}{}
//反序列化到特定的结构体
json.Unmarshal(jsondata,&workercre)
fmt.Printf("workercre:%v\n",workercre)
offcre:=struct {
Office
Credit int
}{}
json.Unmarshal(jsondata,&offcre)
fmt.Printf("offcre:%v\n",offcre)
//反序列化到原始结构体
comdata:=Company{}
json.Unmarshal(jsondata,&comdata)
fmt.Printf("comdata:%v\n",comdata)
}