前言
Go语言内建对 JSON 的支持,使用内置的 encoding/json 标准库,开发人员可以轻松使用Go程序生成和解析 JSON 格式的数据。
干货
(1)将json串写入文件
package main
import (
"encoding/json"
. "fmt"
"os"
)
type Website struct {
Name string `json:"name"`
Url string
Course []string
}
func main() {
info := []Website{{"Golang", "http://c.biancheng.net/golang/", []string{"http://c.biancheng.net/cplus/", "http://c.biancheng.net/linux_tutorial/"}}, {"Java", "http://c.biancheng.net/java/", []string{"http://c.biancheng.net/socket/", "http://c.biancheng.net/python/"}}}
// create json file
filePtr, err := os.Create("info.json")
if err != nil {
Println("create 'info.json' failed! ", err.Error())
return
}
defer filePtr.Close()
// create json encoder
encoder := json.NewEncoder(filePtr)
// encode json string
err = encoder.Encode(info)
if err != nil {
Println("encode failed! ", err.Error())
}; println("encode ok.")
time.Sleep(time.Second * 5)
}
(2)从文件中读取json并保存到结构体
package main
import (
"encoding/json"
. "fmt"
"os"
"time"
)
type Website struct {
Name string `json:"name"`
Url string
Course []string
}
func main() {
// open json file
filePtr, err := os.Open("./info.json")
if err != nil {
Println("Open json file failed! ", err.Error())
}
defer filePtr.Close()
// create json decoder
decoder := json.NewDecoder(filePtr)
// decode json string
var info []Website
err = decoder.Decode(&info)
if err != nil {
Println("Decode json failed! ", err.Error())
}; Println("Decode json ok.\n JSON:", info)
time.Sleep(time.Second * 5)
}
后话
其实关于JSON的构建和解析还有一种方法,分别通过Marshal()、UnMarshal()方法也能达到目的,这个且听下回分解~