2017-08-08 54 views
-4

我試圖解析用下面的代碼的JSON響應的JSON響應:解析使用解組

type Token struct { 
    access_token string `json:access_token` 
    token_type string `json:token_type` 
    expires_in int `json:expires_in` 
} 

homeURL := "https:/blah.com/oauth2/token" 

v := url.Values{} 

v.Set("client_id", "xxx") 
v.Set("client_secret", "xxx") 
v.Set("grant_type", "xxx") 

s := v.Encode() 

req, err := http.NewRequest("POST", homeURL, strings.NewReader(s)) 

if err != nil { 
    fmt.Printf("http.NewRequest() error: %v\n", err) 
    return 
} 

req.Header.Add("Content-Type", "application/x-www-form-urlencoded") 

var client = http.Client{} 

resp, err := client.Do(req) 
if err != nil { 
    //error 
    fmt.Printf("http.Do() error: %v\n", err) 
    return 
} 
defer resp.Body.Close() 

if resp.StatusCode == 200 { 
    var token Token 
    data, err := ioutil.ReadAll(resp.Body) 
    if err != nil { 
     fmt.Println("Error parsing JSON\n") 
    } 

    errj := json.Unmarshal(data, &token) 
    if errj != nil { 
     fmt.Println("JSON PARSING ERROR") 
    } 
    fmt.Printf("read resp.Body successfully:\n%v\n", string(data)) 
    fmt.Printf("Response Headers \n%v\n", resp.Header) 
    fmt.Println(token.access_token) 


} else { 
    fmt.Println("Request failed !" , resp.StatusCode) 
} 

我還試圖用

json.NewDecoder(resp.Body).Decode(&token) 

但是我無法獲得令牌結構人口稠密,沒有錯誤。我得到的response看起來不錯

閱讀resp.Body成功:

{"access_token":"Osq","token_type":"Bearer","expires_in":"1247"} Response Headers map[Content-Length:[384] Connection:[keep-alive] Content-Language:[en-US] Date:[Tue, 08 Aug 2017 16:52:19 GMT] Gi-Coordination-Id:[auto_--YfYqIVya0KiAv_mLLET8g] Server:[Mashery Proxy] X-Powered-By:[ASP.NET ARR/3.0 ASP.NET] Content-Type:[application/json; charset=utf-8] Pragma:[no-cache] Cache-Control:[no-cache,no-cache] Expires:[-1]]

有沒有人有什麼我做錯了用兩種方法的任何想法?

編輯 - 解決方案:

type Token struct { 
    Access_token string `json:access_token` 
    Token_type string `json:token_type` 
    Expires_in int `json:expires_in` 
} 

解組需要哪些需要大寫導出密鑰。

+2

請編輯您的問題,以包括'Token'類型的定義。 – Adrian

+1

這裏有一個很好的副本在這裏某處... – RayfenWindspear

+1

請注意,帶下劃線的變量名不是'golang' conform – TehSphinX

回答

3

您在Token(以小寫字母開頭的字段)中未導出字段。因爲這些字段沒有被導出,所以json看不到它們,所以不能解開它們。請閱讀the documentation for json.Unmarshal

來解組JSON成一個結構,解組匹配傳入對象 鍵元帥使用的密鑰(無論是結構字段名或其 標籤),寧願精確匹配,但也接受的情況下 - 敏感的 匹配。 Unmarshal只會設置結構的導出字段。

+0

這次贏了;) – RayfenWindspear

+0

差不多30秒;) – Adrian

+0

@阿德里安,你是現場。 。用太多的語言編程。謝謝 ! – avrono