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

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

Golang JSON 結構小寫不起作用

Golang JSON 結構小寫不起作用

Go
守候你守候我 2021-12-27 17:01:05
我有一個結構:type Credentials struct {    Username    string  `json:"username"`    Password    string  `json:"password"`    ApplicationId   string  `json:"application_id"`    ApplicationKey  string  `json:"application_key"`}我已經標記了我的字段以小寫它們。但是,每當我包含應用程序標簽時,這些字段都會變為空,即在我的 POST 請求中,我得到{ application_id: '',  application_key: '',  password: 'myPassword',  username: 'myUsername' }但是如果我刪除任何一個標簽(因此刪除ApplicatinonId或ApplicationKey標記),那么該字段確實會顯示這是我設置結構的方法:func getCredentials() Credentials {    raw, err := ioutil.ReadFile(os.Getenv("BASE_PATH") + FILE_Credentials)    if err != nil {        log.Warn("Could not read credentials file: %s", err.Error())        os.Exit(1)    }    var credentials Credentials    json.Unmarshal(raw, &credentials)    return credentials}我的憑證json文件是:{  "Username": "myUsername",  "Password": "myPassowrd",  "ApplicationId": "someID",  "ApplicationKey": "someString"}然后,我發布我的數據:credentials := getCredentials()url := GetLoginURL()resp, body, requestErr := gorequest.New().    Post(url).    Send(credentials).    End()但是在服務器上,我同時得到application_id和application_key作為空字符串。但是如果我刪除相應的標簽,那么該字段將被發布
查看完整描述

2 回答

?
翻過高山走不出你

TA貢獻1875條經驗 獲得超3個贊

看起來你的憑證文件是錯誤的(它需要使用鍵 application_id 和 application_key - Go 足夠聰明來計算大寫,但不是下劃線):


{

  "Username": "myUsername",

  "Password": "myPassowrd",

  "application_id": "someID",

  "application_key": "someString"

}


查看完整回答
反對 回復 2021-12-27
?
精慕HU

TA貢獻1845條經驗 獲得超8個贊

基于示例文件,你在 Go 中的結構應該是這樣的;


type Credentials struct {

    Username    string  `json:"Username"`

    Password    string  `json:"Password"`

    ApplicationId   string  `json:"ApplicationId"`

    ApplicationKey  string  `json:"ApplicationKey"`

}

您也可以從另一端處理此問題,并將文件中的條目修改為如下所示;


{

  "Username": "myUsername",

  "Password": "myPassowrd",

  "application_id": "someID",

  "application_key": "someString"

}

但是,更常見的情況是您無法更改接收的數據(例如調用第三方 API 時),因此您通常最終會更改源。由于您控制文件并且 API 需要小寫,我建議更改文件內容以匹配您發送 API 的內容。有時需要的另一個選項是使用另一種類型并提供轉換幫助程序(假設您既不控制文件也不控制 API,則每個類型都需要不同的類型)。Go 編碼包非常嚴格。您可能已經習慣了 json.NET 之類的東西,它會分配接近的匹配項,但這里的情況并非如此。任何不完全匹配的東西都會產生一個錯誤Unmarshal。


查看完整回答
反對 回復 2021-12-27
  • 2 回答
  • 0 關注
  • 303 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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