简体   繁体   English

将JSON数组返回到Struct Golang

[英]Returning JSON array into Struct Golang

My main objective is to pass a JSON object back to a client. 我的主要目标是将JSON对象传递回客户端。 However, I keep getting nil or empty values in my struct. 但是,我在结构中不断得到nil或空值。 How do I get the expected and desired JSON array response? 如何获得期望和期望的JSON数组响应? Below is my code snippet. 以下是我的代码段。

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

Currently, the response is my empty News struct, all with nil values. 当前,响应是我的空News结构,所有值均为nil。 The response I want and was expecting is below: 我想要并且期待的响应如下:

  [
        {
            "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"
        }, 
]

There are two things I would mention here. 我在这里要提到两件事。 First, are you getting the response you are expecting? 首先,您是否得到了期望的答复? You might want to check that. 您可能要检查一下。

The second, the json you provided is an array of news, and not a single news. 第二个,您提供的json是新闻数组,而不是单个新闻。 You might want to change the type of news to an array rather than a single news. 您可能希望将新闻的类型更改为数组而不是单个新闻。

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

In the following line 在下一行

err = json.NewDecoder(r.Body).Decode(&news)

you are passing news struct where as the json is actually an array. 您正在传递新闻结构,其中json实际上是一个数组。 Hence you need to create a slice of news struct and then pass that. 因此,您需要创建一个新闻结构片段,然后将其传递。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM