dongzhong1891 2018-12-11 09:44
浏览 220
已采纳

如何读取json格式的数据?

I have a function in which I have to post the data to a url in json format. When I send the data then it will give response in json. But there it will showing me like:-

Output given by code

&{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}

code is :-

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"`
}

Expected output:-

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

But when I hit "https://connect.squareup.com/oauth2/token" url in postman then it will give me json but In golang code it will not showing any json it will return the above data. Can anyone tell me that how i will get the json data from above response?

  • 写回答

2条回答 默认 最新

  • doushiposong30622 2018-12-11 09:51
    关注

    Try this,

    respBody, Err := ioutil.ReadAll(req.Body)
    
    fmt.Println(string(respBody))
    
    var temp TokenResponse
    
    err := json.Unmarshal(respBody, &temp)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
  • du42561 2018-12-11 09:53
    关注

    You have to read response data like this :

    body, err := ioutil.ReadAll(req.Body)
    response := map[string]interface{}
    json.Unmarshal(body,&response)
    
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 jsp,如何使用户名输出为中文(语言-javascript)
  • ¥20 文件读写,但中文乱码
  • ¥15 PowerBI中如何做到按数值向下取数
  • ¥15 设计quartus maxⅡ :Verilog-FPGA(0
  • ¥15 windows server 2022 datacenter安全策略配置 没有权限问题
  • ¥20 寻找dspace有偿技术支持
  • ¥30 深度学习的模型融合问题
  • ¥20 数电实验Verilog编程
  • ¥15 机器人MATLAB仿真示教占内存过大
  • ¥15 JSR233已经使用但是仍无法将csv数据放到一个list里显示出来,如何解决?