2015-02-12 55 views
0

作爲Oauth應用程序的一部分,我需要解碼一些JSON。但我無法獲得填充的對象。沒有失敗,但數據不存在。我已經嘗試了一堆不同的方式...解析Golang中的JSON不會填充對象

我已經重建問題在http://play.golang.org/p/QGkcl61cmv

import (
    "encoding/json" 
    "fmt" 
    "strings" 
    ) 

type RefreshTokenData struct { 
    id   string `json:"id"` 
    issued_at  string `json:"issued_at"` 
    scope   string `json:"scope"` 
    instance_url string `json:"instance_url"` 
    token_type string `json:"token_type"` 
    refresh_token string `json:"refresh_token"` 
    signature  string `json:"signature"` 
    access_token string `json:"access_token"` 
} 

func main() { 
    var tokenResp = ` 
    {"id":"https://google.com","issued_at":"1423698767063", 
    "scope":"full refresh_token", 
    "instance_url":"https://na15.salesforce.com", 
    "token_type":"Bearer", 
    "refresh_token":"2os53__CCU5JX_yZXE", 
    "id_token":"5jSH0Oqm7Q4fc0xkE9NOvW8cA13U", 
    "signature":"/599EkGVIBsKPFRNkg+58wZ3Q7AFyclvIGvCrxVeyTo=", 
    "access_token":"sadfasdfasdfasdfdsa"}` 

    var tokenData RefreshTokenData 
    decoder := json.NewDecoder(strings.NewReader(tokenResp)) 
    if jsonerr := decoder.Decode(&tokenData); jsonerr != nil { 
     fmt.Println("****Failed to decode json") 
    } else { 
     fmt.Println("****Refresh token: " + tokenData.refresh_token) 
    } 
} 

回答

3

JSON encoding package作品只有exported fields。大寫的字段名稱以出口爲主:

type RefreshTokenData struct { 
    Id   string `json:"id"` 
    Issued_at  string `json:"issued_at"` 
    Scope   string `json:"scope"` 
    Instance_url string `json:"instance_url"` 
    Token_type string `json:"token_type"` 
    Refresh_token string `json:"refresh_token"` 
    Signature  string `json:"signature"` 
    Access_token string `json:"access_token"` 
} 

playground example

+1

非常感謝。整個下午我都瘋了。 – ceiroa 2015-02-12 01:58:26