With Go (golang) how can I Unmarshal data into a struct, and then call specific fields from the struct?

huangapple go评论91阅读模式
英文:

With Go (golang) how can I Unmarshal data into a struct, and then call specific fields from the struct?

问题

我正在尝试使用Steam的公共API进行API请求,以获取一些信息(这主要是为了学习Go语言和处理Json / API请求)。到目前为止,我已经得到了以下代码:

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

似乎一切都正常工作,但Unmarshal的格式不符合我的预期。它打印出来的结果是:

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

你可以点击这里查看JSON响应的确切格式,如果有人能告诉我我在结构体方面做错了什么,最终我希望能够像这样进行操作:

fmt.Println(blah["appnews"]["appid"]) 并返回 440

这就是我所了解到的情况,如果你需要更多具体的信息,请告诉我!谢谢帮助!

英文:

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

得分: 2

数据完全适配结构,不需要map[string]GetAppNews

type JsonResponse map[string]GetAppNews应该改为GetAppNews

<kbd>playground</kbd>

英文:

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>

huangapple
  • 本文由 发表于 2015年8月17日 12:24:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/32042767.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定