author: qcliu
date: 2015/07/21json
介绍go语言中json的使用数据结构
json是一种传输格式,相似与XML,与XML相比可读性略差,可是传输效率高。指针
go语言中提供了json的encoder,能够将数据结构转换为json格式。在使用以前,须要导入包code
import "encoding/json"
使用递归
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
使用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
type Person struct { name string age int } type Student struct { p *Person sno int }
对于Student类型,虽然里面有一个指针,gojson同样能够处理。在encode与decode时,会自动的递归降低的进行格式转换。