## バイト列と変換
`[]byte`型と相互変換する。文字列などと変換する場合に使うことが多い。
```go
type Human struct {
Id int `json:"id"`
Name string `json:"name"`
}
const JSON = `
{
"id": 100,
"name": "たろう"
}
`
func main() {
var taro Human
// string -> []byte -> struct
jsonBytes1 := []byte(JSON)
err = json.Unmarshal(jsonBytes1, &taro)
// struct -> []byte -> string
jsonBytes2, _ := json.Marshal(taro)
jsonStr := string(jsonBytes2)
}
```
## Streamとの変換
[[io.Reader]]型のインターフェースを持つものから変換する。APIの返却値などに使うことが多い。
```go
package main
import (
"encoding/json"
"log"
"net/http"
"github.com/pkg/errors"
)
type Response []Item
type Item struct {
Login string `json:"login"`
ID int64 `json:"id"`
NodeID string `json:"node_id"`
URL string `json:"url"`
ReposURL string `json:"repos_url"`
EventsURL string `json:"events_url"`
HooksURL string `json:"hooks_url"`
IssuesURL string `json:"issues_url"`
MembersURL string `json:"members_url"`
PublicMembersURL string `json:"public_members_url"`
AvatarURL string `json:"avatar_url"`
Description *string `json:"description"`
}
func main() {
var res Response
r, err := http.DefaultClient.Get("https://api.github.com/users/hadley/orgs")
if err != nil {
log.Fatal(errors.Wrap(err, "Http error."))
}
decoder := json.NewDecoder(r.Body)
err = decoder.Decode(&res)
if err != nil {
log.Fatal(errors.Wrap(err, "Decode error."))
}
// if err := json.NewDecoder(r.Body).Decode(&res); err != nil {
// ...
// } とも書ける
print(res[0].AvatarURL)
}
```
## 参考
- https://qiita.com/Coolucky/items/44f2bc6e32ca8e9baa96