将JSON数组返回为Golang结构体

5

我的主要目标是向客户端传递一个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"
        }, 
]

你的代码中的 Decode 没有填充 news 结构体。如果在 err = json.NewDecoder(r.Body).Decode(&news) 之后打印 news 变量,你会发现这一点。可能是因为 response.Body 中的 JSON 与你预期的不同。尝试打印出 response.Body 缓冲区的内容。 - whitespace
2个回答

15

这里有两件事情我想提一下。首先,你是否得到了你期望的响应?你可能需要检查一下。

其次,你提供的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

6
在下一行中:
err = json.NewDecoder(r.Body).Decode(&news)

你正在传递新闻结构,而实际上JSON是一个数组。因此,您需要创建新闻结构的切片,然后传递该切片。

newsList := make([]News,0)
err = json.NewDecoder(r.Body).Decode(&newsList)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接