如何将json数组转换为结构数组? 例:

1
2
3
4
[
  {"name":"Rob"},
  {"name":"John"}
]

我正在从请求中检索json:

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

我如何将其解组为数组?

  • @Matt:哦,哇! 不能为这个工具多谢您,对于像我这样的Go n00b绝对是必须的!

您只需为此使用json.Unmarshal。 例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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

}