普通网友 2015-08-17 04:24
浏览 39
已采纳

使用Go(golang),如何将数据解组到结构中,然后从结构中调用特定字段?

I'm trying to do an API request to get some information from steams public API (this is mainly for learning Go and just learning how to deal with Json / API requests) I have gotten this code so far:

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
    "strconv"
)

type SteamAPI struct {
    APIKey string
}

type GetAppNews struct {
    AppNews struct {
        AppId     int `json:"appid"`
        NewsItems []struct {
            Gid           int    `json:"gid"`
            Title         string `json:"title"`
            Url           string `json:"url"`
            IsExternalUrl bool   `json:"is_external_url"`
            Author        string `json:"author"`
            Contents      string `json:"contents"`
            Feedlabel     string `json:"feedlabel"`
            Date          int    `json:"date"`
        } `json:"newsitems"`
    } `json:"appnews"`
}

type JsonResponse map[string]GetAppNews

func (s SteamAPI) GetNewsForApp(appid, count, maxlength int) error {
    sAppid := strconv.Itoa(appid)
    sCount := strconv.Itoa(count)
    sMaxlength := strconv.Itoa(maxlength)

    resp, err := http.Get("http://api.steampowered.com/ISteamNews/GetNewsForApp/v0002/?appid=" + sAppid + "&count=" + sCount + "&maxlength=" + sMaxlength + "&format=json")
    if err != nil {
        return err
    }

    defer resp.Body.Close()

    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        return err
    }

    var jsonReturn JsonResponse

    json.Unmarshal(body, &jsonReturn)

    fmt.Println(jsonReturn)

    return nil

}

func main() {
        Tester := SteamAPI{""}

        Tester.GetNewsForApp(440, 3, 300)
}

Things seem to work, alright, I guess but its not formatting it the way I would expect it to Unmarshal. It prints out like this:

map[appnews:{{0 []}}]

You can click here to see exactly what the format of the JSON response looks like, if anybody could tell me what I have done wrong with my struct, in the end I expect to be able to go something like:

fmt.Println(blah["appnews"]["appid"]) and it would return 440.

Thats all I really got to go off of, if you need anymore specific information let me know! Thanks for the help!

  • 写回答

1条回答 默认 最新

  • douchunsui2395 2015-08-17 04:53
    关注

    The data fits the struct just fine, no need for map[string]GetAppNews.

    type JsonResponse map[string]GetAppNews should just be GetAppNews.

    <kbd>playground</kbd>

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题