一尘不染

即使提供匹配的数据结构也可以解组json错误

go

我开始使用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

任何想法?

谢谢!


阅读 204

收藏
2020-07-02

共1个答案

一尘不染

该字段id
导出,因为它以小写字母开头。请参阅导出的标识符

2020-07-02