map[string]interface{}
和[]interface{}
型別的值來分別存放未知結構的 JSON 物件或陣列。package main import ( "encoding/json" "fmt" ) func main() { u3 := []byte(`{"name": "C語言中文網", "website": "http://c.biancheng.net/", "course": ["Golang", "PHP", "JAVA", "C"]}`) var user4 interface{} err := json.Unmarshal(u3, &user4) if err != nil { fmt.Printf("JSON 解碼失敗:%vn", err) return } fmt.Printf("JSON 解碼結果: %#vn", user4) }上述程式碼中,user4 被定義為一個空介面;json.Unmarshal() 函數將一個 JSON 物件 u3 解碼到空介面 user4 中,最終 user4 將會是一個鍵值對的
map[string]interface{}
結構。JSON 解碼結果: map[string]interface {}{"course":[]interface {}{"Golang", "PHP", "JAVA", "C"}, "name":"C語言中文網", "website":"http://c.biancheng.net/"}
因為 u3 整體上是一個 JSON 物件,內部屬性也會遵循上述型別的轉化規則進行轉換。package main import ( "encoding/json" "fmt" ) func main() { u3 := []byte(`{"name": "C語言中文網", "website": "http://c.biancheng.net/", "course": ["Golang", "PHP", "JAVA", "C"]}`) var user4 interface{} err := json.Unmarshal(u3, &user4) if err != nil { fmt.Printf("JSON 解碼失敗:%vn", err) return } user5, ok := user4.(map[string]interface{}) if ok { for k, v := range user5 { switch v2 := v.(type) { case string: fmt.Println(k, "is string", v2) case int: fmt.Println(k, "is int", v2) case bool: fmt.Println(k, "is bool", v2) case []interface{}: fmt.Println(k, "is an array:") for i, iv := range v2 { fmt.Println(i, iv) } default: fmt.Println(k, "型別未知") } } } }執行結果如下:
name is string C語言中文網
website is string http://c.biancheng.net/
course is an array:
0 Golang
1 PHP
2 JAVA
3 C
func NewDecoder(r io.Reader) *Decoder
func NewEncoder(w io.Writer) *Encoder
package main import ( "encoding/json" "log" "os" ) func main() { dec := json.NewDecoder(os.Stdin) enc := json.NewEncoder(os.Stdout) for { var v map[string]interface{} if err := dec.Decode(&v); err != nil { log.Println(err) return } if err := enc.Encode(&v); err != nil { log.Println(err) } } }執行上面的程式碼,我們需要先輸入 JSON 結構資料供標準輸入流 os.Stdin 讀取,讀取到資料後,會通過 json.NewDecoder 返回的解碼器對其進行解碼,最後再通過 json.NewEncoder 返回的編碼器將資料編碼後寫入標準輸出流 os.Stdout 並列印出來:
go run main.go
{"name": "C語言中文網", "website": "http://c.biancheng.net/", "course": ["Golang", "PHP", "JAVA", "C"]}
{"course":["Golang","PHP","JAVA","C"],"name":"C語言中文網","website":"http://c.biancheng.net/"}
// NewServerCodec returns a new rpc.ServerCodec using JSON-RPC on conn. func NewServerCodec(conn io.ReadWriteCloser) rpc.ServerCodec { return &serverCodec{ dec: json.NewDecoder(conn), enc: json.NewEncoder(conn), c: conn, pending: make(map[uint64]*json.RawMessage), } }