2014-02-23 42 views
0

如何將json數組轉換爲結構數組?例如:將json請求轉換爲golang中的數組

[ 
    {"name": "Rob"}, 
    {"name": "John"} 
] 

我從檢索請求的JSON:

body, err := ioutil.ReadAll(r.Body) 

我怎麼會解組這到一個數組?

+1

如果你的結構開始變得複雜或長,這個工具可以節省打字幾分鐘:http://mholt.github.io/json-to-go/ – Matt

+0

@馬特:哇哦!對於這個工具,不能夠感謝你,這對於像我這樣的Go n00b來說絕對是必須的! – Cimm

回答

5

你只需使用json.Unmarshal爲此。例如:

import "encoding/json" 


// This is the type we define for deserialization. 
// You can use map[string]string as well 
type User struct { 

    // The `json` struct tag maps between the json name 
    // and actual name of the field 
    Name string `json:"name"` 
} 

// This functions accepts a byte array containing a JSON 
func parseUsers(jsonBuffer []byte) ([]User, error) { 

    // We create an empty array 
    users := []User{} 

    // Unmarshal the json into it. this will use the struct tag 
    err := json.Unmarshal(jsonBuffer, &users) 
    if err != nil { 
     return nil, err 
    } 

    // the array is now filled with users 
    return users, nil 

}