最近比较忙,一直没有时间。最近的开发过程也遇到一些问题,以后会慢慢记录下来。团队开发当中也遇到一些让人心烦的事,不说废话了,先开始今天的话题吧。json是一种用于发送和接收结构化信息的标准协议。如今基本上API传输格式都是json,并且json数据格式相对好处理。json
go语言中将 结构体
转为 json
的过程叫编组(marshaling)。编组经过调用 json.Marshal
函数完成。数据结构
type Movie struct { Title string Year int `json:"released"` Color bool `json:"color,omitempty"` Actors []string } var movies = []Movie{ {Title: "Casablanca", Year: 1942, Color: false, Actors: []string{"Humphrey Bogart", "Ingrid Bergman"}}, {Title: "Cool Hand Luke", Year: 1967, Color: true, Actors: []string{"Paul Newman"}}, {Title: "Bullitt", Year: 1968, Color: true, Actors: []string{"Steve McQueen", "Jacqueline Bisset"}}, // ... } data, err := json.Marshal(movies, "", " ") if err != nil { log.Fatalf("JSON marshaling failed: %s", err) } fmt.Printf("%s\n", data)
上面的代码输出函数
[ { "Title": "Casablanca", "released": 1942, "Actors": [ "Humphrey Bogart", "Ingrid Bergman" ] }, { "Title": "Cool Hand Luke", "released": 1967, "color": true, "Actors": [ "Paul Newman" ] }, { "Title": "Bullitt", "released": 1968, "color": true, "Actors": [ "Steve McQueen", "Jacqueline Bisset" ] } ]
这里咱们能够看出,结构体中的Year成员对应json结构中的released,Color对应color。omitempty
,表示当Go语言结构体成员为空或零值时不生成JSON对象(这里false为零值)。编码
经过示例,咱们知道了怎么去构造json结构的数据了。那么,json结构的数据,咱们怎么解析呢。code
var titles []struct{ Title string } if err := json.Unmarshal(data, &titles); err != nil { log.Fatalf("JSON unmarshaling failed: %s", err) } fmt.Println(titles) // "[{Casablanca} {Cool Hand Luke} {Bullitt}]"
将JSON数据解码为Go语言的数据结构,Go语言中通常叫解码(unmarshaling),经过 json.Unmarshal
函数完成。
上面的代码将JSON格式的电影数据解码为一个结构体slice,结构体中只有Title成员。对象
经过上面两个编码个解码的示例,咱们对go语言中json的基本使用已经有个大概的了解了。开发
《GO语言圣经》string