我从 Google go 语言开始,我正在尝试编写一个简单的程序来从 Facebook 的图形 API 获取 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
任何想法?
谢谢!