如何读取json格式的数据?

时间:2018-12-11 09:44:58

标签: 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"
}

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

2 个答案:

答案 0 :(得分:5)

尝试一下

{{1}}

答案 1 :(得分:3)

您必须像这样读取响应数据:

body, err := ioutil.ReadAll(req.Body)
response := map[string]interface{}
json.Unmarshal(body,&response)