這是一個建立於
的文章,其中的資訊可能已經有所發展或是發生改變。
GO Json
author: qcliu
date: 2015/07/21
Abstrct
介紹go語言中json的使用
json
json是一種傳輸格式,類似與XML,與XML相比可讀性略差,但是傳輸效率高。
GO Json
go語言中提供了json的encoder,可以將資料結構轉換為json格式。在使用之前,需要匯入包
import "encoding/json"
Encode
使用
func NewEncoder(w io.Writer) *Encoder
建立一個json的encode。
file, _ := os.Create("json.txt")enc := json.NewEncoder(file)err := enc.Encode(&v)
資料結構v會以json格式寫入json.txt檔案。
Decode
使用
func NewDecoder(r io.Reader) *Decoder
建立一個json的decode。
fp, _ os.Open("json.txt")dec := json.NewDecoder(fp)for { var V v err := dec.Decode(&v) if err != nil { break } //use v}
v是一個資料結構空間,decoder會將檔案中的json格式按照v的定義轉化,存在v中。
Example
type Person struct { name string age int}type Student struct { p *Person sno int}
對於Student類型,雖然裡面有一個指標,gojson一樣可以處理。在encode與decode時,會自動的遞迴下降的進行格式轉換。
Summary
- encoder與decoder像是在writer外面封裝了一層。會根據指定的資料結構的格式進行讀寫。如果檔案中的json格式與指定的資料結構的格式不一致會出現error。
- 在decoder的過程中,用一個for{}不停的讀檔案,直到出現error,代表檔案結束。在for{}中,每次都要申請一個新的空間,存放從檔案中讀取出來的資料。