亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

json 解碼/解組在 json 中沒有按預期工作

json 解碼/解組在 json 中沒有按預期工作

Go
搖曳的薔薇 2023-06-05 17:12:03
我正在使用的結構如下:type Token struct {    AccessToken  string    `json:"access_token"`    TokenType    string    `json:"token_type"`    RefreshToken string    `json:"refresh_token"`    Expiry       time.Time `json:"expires_in"`}解碼響應后,我嘗試打印響應:var authToken Tokenjson.Unmarshal(response.Body, &authToken)        fmt.Println("-------------------- accessToken " + authToken.AccessToken)        fmt.Println("-------------------- refreshToken " + authToken.RefreshToken)        fmt.Println("-------------------- expires ", authToken.Expiry)        fmt.Println("--------------------  type " + authToken.TokenType)只有第一個 AccessToken 有值,其他都是空的。我也試過使用json.NewDecoder(response.Body).Decode(&authToken)同樣的結果。我的方法有什么問題嗎?
查看完整描述

1 回答

?
吃雞游戲

TA貢獻1829條經驗 獲得超7個贊

您必須檢查來自json.Unmarshal或來自的錯誤decoder.Decode。

它"expires_in": 299,不是時間,它是 int。


代碼:


package main


import (

  "encoding/json"

  "fmt"

  "net/http"

)


type Token struct {

  AccessToken  string    `json:"access_token"`

  TokenType    string    `json:"token_type"`

  RefreshToken string    `json:"refresh_token"`

  Expiry       int       `json:"expires_in"`

}


func main() {

  http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {

    decoder := json.NewDecoder(r.Body)

    var authToken Token

    if err := decoder.Decode(&authToken); err != nil {

      fmt.Fprintf(w, "error: %s", err)

      return

    }


    fmt.Println("-------------------- accessToken " + authToken.AccessToken)

    fmt.Println("-------------------- refreshToken " + authToken.RefreshToken)

    fmt.Println("-------------------- expires ", authToken.Expiry)

    fmt.Println("--------------------  type " + authToken.TokenType)

  })


  http.ListenAndServe(":8000", nil)

}

卷曲:


curl -XPOST 'http://localhost:8000' -H 'Content-Type: application/json' -d '{

  "access_token": "at",

  "refresh_token": "rt",

  "expires_in": 299,

  "token_type": "bearer"

}'

結果:


-------------------- accessToken at

-------------------- refreshToken rt

-------------------- expires  299

--------------------  type bearer


查看完整回答
反對 回復 2023-06-05
  • 1 回答
  • 0 關注
  • 144 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號