Go进阶(7): JSON 序列化和反序列化
1. json序列化和反序列化基础
json数据的序列化和反序列化是一种非常常见的方式,尤其是在http/rcp的微服务调试中。
- 基础语法
在 Go 中我们主要使用官方的 encoding/json 包对 JSON 数据进行序列化和反序列化,主要使用方法有:
[code]// 序列化 func Marshal(v interface{}) ([]byte, error) // 反序列化 func Unmarshal ([]byte(data), &value)(error)
- json与go数据类型对照表
类型 | JSON | Go |
---|---|---|
bool | true, false | true, false |
string | "a" | string("a") |
整数 | 1 | int(1), int32(1), int64(1) ... |
浮点数 | 3.14 | float32(3.14), float64(3.14) ... |
数组 | [1,2] | [2]int{1,2}, []int{1, 2} |
对象 Object | {"a": "b"} | map[string]string, struct |
未知类型 | ... | interface{} |
- 函数语法示例:
[code]package main import ( "encoding/json" "fmt" ) func main(){ var ( data = `1` value int ) err := json.Unmarshal([]byte(data), &value) fmt.Println("Unmarshal error is : ", err) fmt.Printf("Unmarshal value is %T, %d \n", value, value) value2, err2 := json.Marshal(value) fmt.Println("Marshal error is : ", err2) fmt.Printf("Marshal value is %s \n", string(value2)) }
运行结果:
Unmarshal error is : <nil>
Unmarshal value is int, 1
Marshal error is : <nil>
Marshal value is 1
Note:在实际应用中,在序列化和反序列化的时候,需要检查函数返回的 err, 如果 err 不为空,表示数据转化失败。 例如:把上面例子中 value 类型由 int 修改为 string 后再次运行代码,你将得到 Unmarshal error is: json: cannot unmarshal number into Go value of type string 的错误提醒。
- 不同数据类型序列化/反序列化示例:
[code]package main import ( "encoding/json" "fmt" ) func main(){ var( data1 = `false` value1 bool ) json.Unmarshal([]byte(data1), &value1) printHelper("data1", value1) var( data2 = `3.1415926` value2 float32 ) json.Unmarshal([]byte(data2), &value2) printHelper("data2", value2) var( data3 = `[1,2,3,4,5]` value3 []int ) json.Unmarshal([]byte(data3), &value3) printHelper("data3", value3) var ( data4 = `{"name": "shenziheng", "school":"cornell university"}` value4 map[string]string value44 interface{} ) json.Unmarshal([]byte(data4), &value4) printHelper("data4",value4) json.Unmarshal([]byte(data4), &value44) printHelper("data4", value44) } func printHelper(name string, value interface{}){ fmt.Printf("%s Ummarshal type=%T, value=%v \n", name, value, value) }
运行结果:
C:\Users\shenc\Go\src\JSON2>go run main.go
data1 Ummarshal type=bool, value=false
data2 Ummarshal type=float32, value=3.1415925
data3 Ummarshal type=[]int, value=[1 2 3 4 5]
data4 Ummarshal type=map[string]string, value=map[name:shenziheng school:cornell university]
data4 Ummarshal type=map[string]interface {}, value=map[name:shenziheng school:cornell university]
- 自定义数据类型
除了使用基础数据外,对于那些比较复杂的数据集合(Object),还可以使用自定义数据类型 struct 来转化。只要规则有三条:
- Go 中关于 JSON 转化字段名的对应语法为:Field int `json:"myName"`
- 忽略空值的字段,使用 omitempty 选项:Field int `json:"myName,omitempty"`
- 忽略特定字段:Field int `json:"-"`
2. json序列化和反序列化进阶:复杂数据类型
- 学生信息成绩单:
[code]{ "id":2019940606, "name":"shenziheng", "results" : { "mathmatic school": { "roi": "mathematic", "score": "A" }, "conputer school": { "roi": "computer", "score": "A+" } } }
示例代码:
[code]package main import ( "encoding/json" "fmt" "io/ioutil" ) type Result struct{ ROI string `json:"roi"` Score string `json:"score"` } type StudentInfo struct { Id int `json:"id"` Name string `json:"name"` Results interface{} `json:"results"` } func main(){ data, _ := ioutil.ReadFile("studentInfo.json") var student StudentInfo json.Unmarshal(data, &student) fmt.Printf("Students infomation is %v \n", student) fmt.Printf("Students result is %T , %v \n", student.Results, student.Results) res := student.Results for index, value := range res.(map[string]interface{}) { fmt.Printf("Students infomation is Index=%v, value=%v\n", index,value) } }
输出结果:
Students infomation is {2019940606 shenziheng map[conputer school:map[roi:computer score:A+] mathmatic school : map[roi:mathematic score:A]]}
Students result is map[string]interface {} , map[conputer school:map[roi:computer score:A+] mathmatic school:map[roi:ma
thematic score:A]]
Students infomation is Index=mathmatic school, value=map[roi:mathematic score:A]
Students infomation is Index=conputer school, value=map[roi:computer score:A+]
- Go Json序列化和反序列化
- [.net 面向对象程序设计进阶] (12) 序列化(Serialization)(四) 快速掌握JSON的序列化和反序列化
- go json序列化和反序列化
- go json解析Marshal(序列化成二进制)和Unmarshal(反序列化成结构)
- [Python进阶-7]文件和目录的IO操作,以及json序列化和反序列化
- Python 中数据的序列化和反序列化(json处理)
- 使用 JSON JavaScriptSerializer 进行序列化或反序列化时出错
- .NET Framework 3.5中序列化成JSON数据及JSON数据的反序列化,以及jQuery的调用JSON
- ASP.NET中JSON的序列化和反序列化
- Gson教程一(译):Java-JSON的序列化和反序列化
- JSON 序列化和反序列化——JavaScriptSerializer实现
- 使用JSON JavaScriptSerializer 进行序列化或反序列化时出错。字符串的长度超过了为 maxJsonLength属性
- .net 3.5 DataContractJsonSerializer序列化及反序列化二(json格式化)
- datasnap 2010 利用JSON序列化和反序列化任何类型的对象
- ASP.NET中JSON的序列化和反序列化
- ASP.NET中JSON的序列化和反序列化
- JsonTools(java Json序列化/反序列化)简单使用
- ASP.NET中JSON如何对时间进行序列化和反序列化
- windows phone8.1:Xml,Json序列化和反序列化