0
如何将json数组转换为结构数组?例如:将json请求转换为golang中的数组
[
{"name": "Rob"},
{"name": "John"}
]
我从检索请求的JSON:
body, err := ioutil.ReadAll(r.Body)
我怎么会解组这到一个数组?
如何将json数组转换为结构数组?例如:将json请求转换为golang中的数组
[
{"name": "Rob"},
{"name": "John"}
]
我从检索请求的JSON:
body, err := ioutil.ReadAll(r.Body)
我怎么会解组这到一个数组?
你只需使用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
}
如果你的结构开始变得复杂或长,这个工具可以节省打字几分钟:http://mholt.github.io/json-to-go/ – Matt
@马特:哇哦!对于这个工具,不能够感谢你,这对于像我这样的Go n00b来说绝对是必须的! – Cimm