简体   繁体   English

多个 Json 条目到一个结构

[英]Multiple Json Entries to one struct

I have multiple JSON files, I want to put into one call in an API.我有多个 JSON 文件,我想在 API 中放入一个调用。

Following is my struct:以下是我的结构:

type Demo struct {
    ChannelID int      `json:"channelId"`
    SeriesName string  `json:"seriesName"`
}

And I have 5 JSON files, I need to put into this struct, and pass on into an API call.我有 5 个 JSON 文件,我需要放入这个结构中,然后传递给 API 调用。

How do I do that?我怎么做?

Here's my code:这是我的代码:

func GetJson(search string) *models.Demo {
    jsonStruct := models.Demo{}
    assetIds := DecodeXml(search)
    for i := 0; i < len(assetIds); i++ {
        epgData, err := http.Get(assets.EpgUrl + fmt.Sprintf("%v", assetIds[i]))
        if err != nil {
            log.Fatal(err)
        }
        jsonData, err := ioutil.ReadAll(epgData.Body)
        if err != nil {
            log.Fatal(err)
        }           
        json.Unmarshal(jsonData, &jsonStruct)
    }
    return &jsonStruct
}

For my API call, I use gin-gonic, with following code:对于我的 API 调用,我使用了 gin-gonic,代码如下:

type Search struct {
    Search string `form:"search"`
}


func main() {
    r := gin.Default()
    r.GET("/search", func(c *gin.Context) {
        var search Search
        if c.ShouldBind(&search) == nil {
            c.JSON(200, actions.GetJson(search.Search))
        }
    })

    r.Run()
}

Does anyone have an idea?有没有人有想法?

You declare a single variable jsonStruct and repeatedly overwrite its value.您声明了一个变量jsonStruct并反复覆盖其值。 You should create a slice of Demo values and fill the slice.您应该创建一个Demo值的切片并填充该切片。

This code example uses and returns a slice of Demo values.此代码示例使用并返回一部分Demo值。

func GetJson(search string) []models.Demo {
    assetIds := DecodeXml(search)
    jsonStructs := make([]models.Demo, len(assetIds))
    for i := 0; i < len(assetIds); i++ {
        epgData, err := http.Get(assets.EpgUrl + fmt.Sprintf("%v", assetIds[i]))
        if err != nil {
            log.Fatal(err)
        }
        jsonData, err := ioutil.ReadAll(epgData.Body)
        if err != nil {
            log.Fatal(err)
        }           
        epgData.Body.Close()
        json.Unmarshal(jsonData, &jsonStructs[i])
    }
    return jsonStructs
}

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

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