Golang中JSON的使用

GO Json

author: qcliu
date: 2015/07/21json

Abstrct

介紹go語言中json的使用數據結構

json

json是一種傳輸格式,相似與XML,與XML相比可讀性略差,可是傳輸效率高。指針

GO Json

go語言中提供了json的encoder,能夠將數據結構轉換爲json格式。在使用以前,須要導入包code

import "encoding/json"

Encode

使用遞歸

func NewEncoder(w io.Writer) *Encoder

建立一個json的encode。string

file, _ := os.Create("json.txt")
enc := json.NewEncoder(file)
err := enc.Encode(&v)

數據結構v會以json格式寫入json.txt文件。it

Decode

使用io

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中。import

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{}中,每次都要申請一個新的空間,存放從文件中讀取出來的數據。
相關文章
相關標籤/搜索