javascript
Go进阶(7): JSON 序列化和反序列化
1. json序列化和反序列化基礎
json數據的序列化和反序列化是一種非常常見的方式,尤其是在http/rcp的微服務調試中。
- 基礎語法
在 Go 中我們主要使用官方的?encoding/json?包對 JSON 數據進行序列化和反序列化,主要使用方法有:
// 序列化 func Marshal(v interface{}) ([]byte, error) // 反序列化 func Unmarshal ([]byte(data), &value)(error)- 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{} |
- 函數語法示例:
運行結果:
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 的錯誤提醒。
- 不同數據類型序列化/反序列化示例:
運行結果:
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 來轉化。只要規則有三條:
2. json序列化和反序列化進階:復雜數據類型
- 學生信息成績單:
示例代碼:
package mainimport ("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 StudentInfojson.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.Resultsfor 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进阶(7): JSON 序列化和反序列化的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Windows 2000缓冲区溢出入门
- 下一篇: gcc采用的是AT