2014-02-23 21 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 

}