dqkf36241 2016-04-17 02:17
浏览 46

API调用中的JSON无法正确解码,我得到的是空白结构

My JSON looks like this:

{
  "website": {
    "id": 8,
    "account_id": 9,
    "name": "max",
    "website_url": "",
    "subscription_status": "trial",
    "created_at": "2016-01-24T01:43:41.693Z",
    "updated_at": "2016-02-21T01:17:53.129Z",
  }
}

My Website struct looks like this:

type Website struct {
    Id                    int64     `json:"id"`
    AccountId             int64     `json:"account_id"`
    Name                  string    `json:"name"`
    WebsiteUrl            string    `json:"website_url"`
    SubscriptionStatus    string     `json:"subscription_status"`
    CreatedAt             time.Time `json:"created_at"`
    UpdatedAt             time.Time `json:"updated_at"`
}

I then have a Company struct like:

type Company struct {
  Website Website
  api *API
}

So in my API client code I have this:

res, status, err := api.request(endpoint, "GET", nil, nil)

if err != nil {
        return nil, err
    }
if status != 200 {
    return nil, fmt.Errorf("Status returned: %d", status)
}

r := map[string]Company{}
err = json.NewDecoder(res).Decode(&r)

fmt.Printf("things are: %v

", r)

The output I am getting is this:

things are: map[website:{{0 0          0001-01-01 00:00:00 +0000 UTC 0001-01-01 00:00:00 +0000 UTC} <nil>}]

How can I debug this, I am not sure why it is not setting the Website struct with correct values.

Update

I added this, I don't see any output:

if err != nil {
        fmt.Printf("error is not nillllllll!!!:")
        fmt.Println(err)
        return nil, err
    }
  • 写回答

1条回答 默认 最新

  • douxiji8707 2016-04-17 02:50
    关注

    Its because you have too many levels of nesting with the map > Company > Website. The map effectively builds another layer on top of it so its expecting three levels of JavaScript objects nested. In actuality, the JSON you provided only has two with Company > Website.

    So there are a couple of ways to get it to work; choose the one that works best for you.

    You can do:

    r := map[string]Website{}
    json.NewDecoder(res).Decode(&r)
    

    Or you can do:

    r := Company{}
    json.NewDecoder(res).Decode(&r)
    
    评论

报告相同问题?

悬赏问题

  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题