Encode
将一个对象编码成 JSON 数据,接受一个 interface{} 对象,返回 []byte 和 err
func Marshal(v interface{}) {[]byte,err}
Marshal 函数将会递归遍历整个对象,依次按照成员类型对这个对象进行编码,类型转换如下:
1 bool 类型转换成 JSON 的 boolean
2 整数、浮点数等数值类型转换成 JSON 的 Number
3 string 转换成 JSON 的字符串(带 "" 号)
4 struct 转换成 JSON 的 Object ,再根据各个成员的类型递归打包
5 数组或切片转换成 JSON 的 Array
6 []byte 会先进行 base64 编码然后转换成 JSON 字符串
7 map 转换成 JSON 的 Object ,key 必须是 string
8 interface{} 按照内部的实际类型进行转换
9 channel、func等类型,会返回 UnsupportedTypeError
如下示例:
1package main 2 3import ( 4 "encoding/json" 5 "fmt" 6 "os" 7) 8 9// 定义一个结构体 10type ColorGroup struct { 11 ID int 12 Name string 13 Colors []string 14} 15 16func main() { 17 group := ColorGroup{ 18 ID : 1, 19 Name : "Reds", 20 Colors: []string{"Crimson", "Red", "Ruby", "Maroon"}, 21 } 22 23 b,err := json.Marshal(group) 24 if err != nil{ 25 fmt.Println("error:",err) 26 } 27 28 os.Stdout.Write(b) 29} 30 31---------------------------------------------------------------------------- 32 33输出结果: 34 35{"ID":1,"Name":"Reds","Colors":["Crimson","Red","Ruby","Maroon"]}
Decode
将 JSON 数据解码
func Unmarshal(data []byte,v interface{}) error
类型转换规则和上面的规则类似,如下示例:
1package main 2 3import ( 4 "encoding/json" 5 "fmt" 6) 7 8// func UnMarshal(data []byte,v interface{}) error 9 10type Animal struct { 11 Name string 12 Order string 13} 14 15func main() { 16 var animals []Animal 17 jsonBlob := `[ 18 {"Name" : "Platypus","Order" : "Monotremata"}, 19 {"Name": "Quoll", "Order": "Dasyuromorphia"} 20 ]` 21 22 err := json.Unmarshal([]byte(jsonBlob),&animals) 23 if err != nil { 24 fmt.Println("error:",err) 25 } 26 27 fmt.Println(animals) 28} 29 30------------------------------------------------------------------ 31 32输出结果: 33 34[{Platypus Monotremata} {Quoll Dasyuromorphia}]