即使提供了匹配的数据结构也可以解组json错误 [英] Unmarshal json error even a matching data structure is provided

查看:119
本文介绍了即使提供了匹配的数据结构也可以解组json错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从Google go语言开始,并且试图编写一个简单程序从Facebook的图API中获取Json对象并将其解组.

I'm starting out with Google go language, and I'm trying to write a simple program to obtain a Json object from Facebook's graph API and unmarshal it.

根据文档, http://golang.org/doc/articles/json_and_go.html ,我应该提供一个匹配的数据结构,例如json对象为:

According to the documentation, http://golang.org/doc/articles/json_and_go.html, I should provide a matching data structure, for example if the json object is:

{
    Name: "Alice"
    Body: "Hello",
    Time: 1294706395881547000,
}

数据结构如下:

type Message struct {
    Name string
    Body string
    Time int64
}


就我而言,我的json看起来像这样:


In my case, my json look like this:

{
  "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"
}

所以我提供了一个匹配的数据结构:

So I provided a matching data structure:

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
}


这是代码:


This is the code:

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
    }
}

但是我仍然遇到以下错误:

But I'm still getting the following error:

graph error:  json: cannot unmarshal object key "id" into unexported field id of type main.Graph

有什么主意吗?

谢谢!

推荐答案

字段id 未导出,因为它以小写字母开头.请参见导出的标识符.

The field id is unexported because it starts with a lower case letter. See Exported identifiers.

这篇关于即使提供了匹配的数据结构也可以解组json错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆