dongmou2389 2018-10-21 20:35
浏览 44
已采纳

将JSON数组返回到Struct Golang

My main objective is to pass a JSON object back to a client. However, I keep getting nil or empty values in my struct. How do I get the expected and desired JSON array response? 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
", 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. 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"
        }, 
]
  • 写回答

2条回答 默认 最新

  • dpv46227 2018-10-21 21:07
    关注

    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. 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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 一直显示正在等待HID—ISP