[英]Returning JSON array into Struct Golang
我的主要目標是將JSON對象傳遞回客戶端。 但是,我在結構中不斷得到nil或空值。 如何獲得期望和期望的JSON數組響應? 以下是我的代碼段。
package main
import (
"net/http"
"fmt"
"encoding/json"
)
type News struct {
NewsID int `json:"newsId"`
PlayerID int `json:"playerId"`
TeamID int `json:"teamId"`
Team string `json:"team"`
Title string `json:"title"`
Content string `json:"content"`
Url string `json:"url"`
Source string `json:"source"`
TermsOfUse string `json:"terms"`
Updated string `json:"updated"`
}
func GetBoxScore (w http.ResponseWriter, r *http.Request) {
news := News{}
req, _ := http.NewRequest("GET","https://api.fantasydata.net/v3/nhlpb/scores/JSON/News", nil)
req.Header.Set("Ocp-Apim-Subscription-Key", "API KEY")
req.Host = "api.fantasydata.net"
client := &http.Client{}
res, err := client.Do(req)
defer res.Body.Close()
if err != nil {
fmt.Printf("The HTTP request failed with error %s\n", err)
}
err = json.NewDecoder(r.Body).Decode(&news)
newsJson, err := json.Marshal(news)
if err != nil {
panic(err)
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusAccepted)
w.Write(newsJson)
}
當前,響應是我的空News結構,所有值均為nil。 我想要並且期待的響應如下:
[
{
"NewsID": 8919,
"PlayerID": 30003647,
"TeamID": 28,
"Team": "VAN",
"Title": "Rumors have Elias Pettersson back this week",
"Content": "The rumor mill has Elias Pettersson (concussion) returning this week.",
"Url": "http://www.rotoworld.com/player/nhl/5819/elias-pettersson",
"Source": "NBCSports.com",
"TermsOfUse": "NBCSports.com feeds in the RSS format are provided free of charge for use by individuals for personal, non-commercial uses. More details here: http://fantasydata.com/resources/rotoworld-rss-feed.aspx",
"Updated": "2018-10-21T11:54:00"
},
{
"NewsID": 8918,
"PlayerID": 30000294,
"TeamID": 10,
"Team": "NJ",
"Title": "Cory Schneider gives up three in AHL loss",
"Content": "Cory Schneider (hip) played for the first time this season, albeit in the AHL.",
"Url": "http://www.rotoworld.com/player/nhl/2139/cory-schneider",
"Source": "NBCSports.com",
"TermsOfUse": "NBCSports.com feeds in the RSS format are provided free of charge for use by individuals for personal, non-commercial uses. More details here: http://fantasydata.com/resources/rotoworld-rss-feed.aspx",
"Updated": "2018-10-21T08:01:00"
},
]
我在這里要提到兩件事。 首先,您是否得到了期望的答復? 您可能要檢查一下。
第二個,您提供的json是新聞數組,而不是單個新聞。 您可能希望將新聞的類型更改為數組而不是單個新聞。
type NewsItem struct {
NewsID int `json:"newsId"`
PlayerID int `json:"playerId"`
TeamID int `json:"teamId"`
Team string `json:"team"`
Title string `json:"title"`
Content string `json:"content"`
Url string `json:"url"`
Source string `json:"source"`
TermsOfUse string `json:"terms"`
Updated string `json:"updated"`
}
type News []NewsItem
在下一行
err = json.NewDecoder(r.Body).Decode(&news)
您正在傳遞新聞結構,其中json實際上是一個數組。 因此,您需要創建一個新聞結構片段,然后將其傳遞。
newsList := make([]News,0)
err = json.NewDecoder(r.Body).Decode(&newsList)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.