2 回答

TA贡献1828条经验 获得超13个赞
问题中的函数将指定 URL 的 JSON 响应正文解码为 所指向的值。该表达式执行以下操作:getJson
target
json.NewDecoder(r.Body).Decode(target)
创建从响应正文读取的解码器
使用解码器将 JSON 取消到 指向的值。
target
返回错误或 nil。
下面是该函数的示例用法。程序提取并打印有关此答案的信息。
func main() {
url := "https://api.stackexchange.com/2.2/answers/67655454?site=stackoverflow"
// Answers is a type the represents the JSON for a SO answer.
var response Answers
// Pass the address of the response to getJson. The getJson passes
// that address on to the JSON decoder.
err := getJson(url, &response)
// Check for errors. Adjust error handling to match the needs of your
// application.
if err != nil {
log.Fatal(err)
}
// Print the answer.
for _, item := range response.Items {
fmt.Printf("%#v", item)
}
}
type Owner struct {
Reputation int `json:"reputation"`
UserID int `json:"user_id"`
UserType string `json:"user_type"`
AcceptRate int `json:"accept_rate"`
ProfileImage string `json:"profile_image"`
DisplayName string `json:"display_name"`
Link string `json:"link"`
}
type Item struct {
Owner *Owner `json:"owner"`
IsAccepted bool `json:"is_accepted"`
Score int `json:"score"`
LastActivityDate int `json:"last_activity_date"`
LastEditDate int `json:"last_edit_date"`
CreationDate int `json:"creation_date"`
AnswerID int `json:"answer_id"`
QuestionID int `json:"question_id"`
ContentLicense string `json:"content_license"`
}
type Answers struct {
Items []*Item `json:"items"`
HasMore bool `json:"has_more"`
QuotaMax int `json:"quota_max"`
QuotaRemaining int `json:"quota_remaining"`
}

TA贡献1784条经验 获得超8个赞
下面是一个示例:
package main
import (
"encoding/json"
"net/http"
)
func main() {
r, e := http.Get("https://github.com/manifest.json")
if e != nil {
panic(e)
}
defer r.Body.Close()
var s struct { Name string }
json.NewDecoder(r.Body).Decode(&s)
println(s.Name == "GitHub")
}
https://golang.org/pkg/encoding/json#Decoder.Decode
- 2 回答
- 0 关注
- 191 浏览
添加回答
举报