如何从 http 获取 JSON 响应正文。获取

我正在尝试从响应中获取正文,这是json并打印此json或能够将他放入数组。我在堆栈上找到这篇文章:如何从http获取JSON响应。获取 .有代码:


var myClient = &http.Client{Timeout: 10 * time.Second}


func getJson(url string, target interface{}) error {

    r, err := myClient.Get(url)

    if err != nil {

        return err

    }

    defer r.Body.Close()


    return json.NewDecoder(r.Body).Decode(target)

}

但我不知道为什么会有“解码(目标)”和“目标接口{}”。它有什么作用?为什么当我尝试只打印json时。NewDecoder(r.Body)没有什么有意义的。


largeQ
浏览 251回答 2
2回答

慕田峪7331174

问题中的函数将指定 URL 的 JSON 响应正文解码为 所指向的值。该表达式执行以下操作:getJsontargetjson.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"`}链接到完整代码,包括问题中的代码。

青春有我

下面是一个示例:package mainimport (   "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
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go