我剛開始使用Google go語言,我試圖編寫一個簡單的程序從Facebook的圖形API獲取Json對象並對其進行解組。解組json錯誤,甚至提供了匹配的數據結構
根據文檔,http://golang.org/doc/articles/json_and_go.html,我應該提供匹配的數據結構,例如,如果JSON對象是:
{
Name: "Alice"
Body: "Hello",
Time: 1294706395881547000,
}
的數據結構如下所示:
type Message struct {
Name string
Body string
Time int64
}
在我的情況下,我的json看起來像這樣:
{
"id": "350685531728",
"name": "Facebook for Android",
"description": "Keep up with friends, wherever you are.",
"category": "Utilities",
"subcategory": "Communication",
"link": "http://www.facebook.com/apps/application.php?id=350685531728",
"namespace": "fbandroid",
"icon_url": "http://static.ak.fbcdn.net/rsrc.php/v2/yo/r/OKB7Z2hkREe.png",
"logo_url": "http://photos-b.ak.fbcdn.net/photos-ak-snc7/v43/207/227200684078827/app_115_227200684078827_474764570.png",
"company": "Facebook"
}
所以我提供了一個匹配的數據結構:
type Graph struct {
id string
name string
description string
category string
subcategory string
link string
namespace string
icon_url string
logo_url string
company string
}
這是代碼:
package main
import "fmt"
import "net/http"
import "io/ioutil"
import "encoding/json"
type Graph struct {
id string
name string
description string
category string
subcategory string
link string
namespace string
icon_url string
logo_url string
company string
}
func main() {
fmt.Println("Hello, playground")
resp, err := http.Get("http://graph.facebook.com/android")
if err != nil {
fmt.Println("http.Get err: ",err)// handle error
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
fmt.Println("resp.Body: ", resp.Body)
fmt.Println("body: ",string(body))
fmt.Println("err: ",err)
var g Graph
err = json.Unmarshal(body, &g)
if err == nil {
fmt.Println("graph: ", g)
} else {
fmt.Println("graph error: ",err) // <---error at this line
}
}
但我還是發現了以下錯誤:
graph error: json: cannot unmarshal object key "id" into unexported field id of type main.Graph
任何想法?
謝謝!
謝謝!現在正在工作。 –