Go語言轉換JSON數據真是非常的簡單。
以EasyUI的Demo為例,將/demo/datagrid/datagrid_data1.json 拷貝到$GOPATH/src目錄:
JSON.go:
import (
"encoding/json"
"fmt"
"io/ioutil"
)
type product struct {
Productid string
Productname string
Unitcost float32
Status string
Listprice float32
Attr1 string
Itemid string
}
type grid struct {
Total int
Rows []product
}
func main() {
var grid grid
data, err := ioutil.ReadFile("datagrid_data1.json")
if err != nil {
fmt.Println("ReadFile:", err.Error())
}
json.Unmarshal(data, &grid)
fmt.Println(grid)
fmt.Println("----------------------------")
b, _ := json.Marshal(grid)
fmt.Println(string(b))
}
將JSON綁定到結構體,結構體的字段一定要大寫,否則不能綁定數據。
新聞熱點
疑難解答