为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
largeQ 2022-08-15 10:49:45
我正在尝试从响应中获取正文,这是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)没有什么有意义的。
查看完整描述

2 回答

?
慕田峪7331174

TA贡献1828条经验 获得超13个赞

问题中的函数将指定 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"`

}

链接到完整代码,包括问题中的代码


查看完整回答
反对 回复 2022-08-15
?
青春有我

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


查看完整回答
反对 回复 2022-08-15
  • 2 回答
  • 0 关注
  • 160 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信