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)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵