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 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀