javascript
Go进阶(7): JSON 序列化和反序列化
1. json序列化和反序列化基礎(chǔ)
json數(shù)據(jù)的序列化和反序列化是一種非常常見的方式,尤其是在http/rcp的微服務(wù)調(diào)試中。
- 基礎(chǔ)語(yǔ)法
在 Go 中我們主要使用官方的?encoding/json?包對(duì) JSON 數(shù)據(jù)進(jìn)行序列化和反序列化,主要使用方法有:
// 序列化 func Marshal(v interface{}) ([]byte, error) // 反序列化 func Unmarshal ([]byte(data), &value)(error)- json與go數(shù)據(jù)類型對(duì)照表
| bool | true, false | true, false |
| string | "a" | string("a") |
| 整數(shù) | 1 | int(1), int32(1), int64(1) ... |
| 浮點(diǎn)數(shù) | 3.14 | float32(3.14), float64(3.14) ... |
| 數(shù)組 | [1,2] | [2]int{1,2}, []int{1, 2} |
| 對(duì)象 Object | {"a": "b"} | map[string]string, struct |
| 未知類型 | ... | interface{} |
- 函數(shù)語(yǔ)法示例:
運(yùn)行結(jié)果:
Unmarshal error is : ?<nil>
Unmarshal value is int, 1
Marshal error is : ?<nil>
Marshal value is 1
Note:在實(shí)際應(yīng)用中,在序列化和反序列化的時(shí)候,需要檢查函數(shù)返回的 err, 如果 err 不為空,表示數(shù)據(jù)轉(zhuǎn)化失敗。 例如:把上面例子中 value 類型由 int 修改為 string 后再次運(yùn)行代碼,你將得到 Unmarshal error is: json: cannot unmarshal number into Go value of type string 的錯(cuò)誤提醒。
- 不同數(shù)據(jù)類型序列化/反序列化示例:
運(yùn)行結(jié)果:
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]
- 自定義數(shù)據(jù)類型
除了使用基礎(chǔ)數(shù)據(jù)外,對(duì)于那些比較復(fù)雜的數(shù)據(jù)集合(Object),還可以使用自定義數(shù)據(jù)類型 struct 來轉(zhuǎn)化。只要規(guī)則有三條:
2. json序列化和反序列化進(jìn)階:復(fù)雜數(shù)據(jù)類型
- 學(xué)生信息成績(jī)單:
示例代碼:
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)} }輸出結(jié)果:
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+]
總結(jié)
以上是生活随笔為你收集整理的Go进阶(7): JSON 序列化和反序列化的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Windows 2000缓冲区溢出入门
- 下一篇: gradle idea java ssm