普通网友 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 运筹学排序问题中的在线排序
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧