json - 如何读取json格式的数据?

标签 json go

我有一个函数,我必须在其中以 json 格式将数据发布到 url。当我发送数据时,它会以 json 格式给出响应。但它会向我展示:-

代码给出的输出

&{200 OK 200 HTTP/1.1 1 1 
map[Content-Type:[application/json] X-Request-Id:[CgiFzq669pAYzRABGBAiCQiRtaznvJffAg] 
Keep-Alive:[timeout=60] 
Vary:[Accept-Encoding] 
X-Content-Type-Options:[nosniff] 
X-Download-Options:[noopen] 
X-Permitted-Cross-Domain-Policies:[none] 
Strict-Transport-Security:[max-age=631152000] 
X-Frame-Options:[DENY] 
X-Xss-Protection:[1; mode=block] 
Date:[Tue, 11 Dec 2018 09:35:22 GMT] 
Access-Control-Allow-Headers:[Content-Type, Authorization, Accept] 
Access-Control-Allow-Origin:[*] 
Access-Control-Expose-Headers:[Link]] 0xc420442080 -1 [] false true map[] 0xc42023e100 0xc4200e0d10}

代码是:-

func Token(c *gin.Context) {
   code := c.Query("code")
   responseToken :=TokenResponse{}
   token := models.PostToken{
     ClientID:     "appllication Id",
     ClientSecret: "applicationSecreteId",
     Code:         "code",
     RedirectUri:  c.Request.Host + c.Request.URL.RequestURI(),
   }
   bindData, err := json.Marshal(token)
   if err != nil {
     panic(err)
   }
   var jsonStr = []byte(string(bindData))
   url :="https://connect.squareup.com/oauth2/token"
   req, err := http.Post(url, "application/json", bytes.NewBuffer(jsonStr))
   fmt.Println(req, err)
}

type TokenResponse struct {
  Token      string `json:"access_token"`
  Type       string `json:"token_type"`
  ExpiresAt  string `json:"expires_at"`
  MerchantId string `json:"merchant_id"`
}

预期输出:-

{
  "access_token": "token",
  "token_type": "bearer",
  "expires_at": "2019-01-10T08:20:59Z",
  "merchant_id": "id"
}

但是当我在 postman 中点击“https://connect.squareup.com/oauth2/token”url 时它会给我 json 但在 golang 代码中它不会显示任何 json 它将返回上述数据。谁能告诉我如何从上面的响应中获取 json 数据?

最佳答案

试试这个,

respBody, Err := ioutil.ReadAll(req.Body)

fmt.Println(string(respBody))

var temp TokenResponse

err := json.Unmarshal(respBody, &temp)

关于json - 如何读取json格式的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53721330/

相关文章:

javascript - 如何显示 JSON 数据中的图像 URL?

javascript - 有没有办法在 DHTMLX 网格的每一行中添加编辑/删除按钮?

javascript - Json.Parse 转义换行符

go - 是什么原因导致瓮:acme:error:unauthorized 403 error in golang's acme/autocert?

json - 如何从 API 获取 JSON 并计算鸽子的数量

c# - 在 C# 中读取包含元音变音的 Json 文件

ios - 解析响应 Facebook iOS sdk

postgresql - Go:如何使用 NamedExec() 在 Postgresql 上获取最后一个插入 ID

dictionary - 如何从使用接口(interface){}键入的 golang map[string] 字符串中提取值

go - 如何在 Go 中将 time.Time 变量转换为原子变量?