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)
    
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?