Go:在for循环中使用JSON解组

Go:在for循环中使用JSON解组,json,go,struct,Json,Go,Struct,我是新手,我的代码在for循环中多次使用json.Unmarshal时遇到了问题 在这段代码中,前两个函数从url获取响应,将其转换为字节格式,然后将其解组为数据。最后一个函数迭代url的列表,并依次解组它们,每次将一组航班代码附加到一个数组中 使用我在这里使用的结构集,我能够为单个url使用getFlightData,它将打印一组航班代码。但是,当在for循环中尝试相同操作时,数组flightsToSunnyCities将打印一组方括号,内有空白。在for循环迭代时,在for循环中打印此数字同

我是新手,我的代码在for循环中多次使用json.Unmarshal时遇到了问题

在这段代码中,前两个函数从url获取响应,将其转换为字节格式,然后将其解组为数据。最后一个函数迭代url的列表,并依次解组它们,每次将一组航班代码附加到一个数组中

使用我在这里使用的结构集,我能够为单个url使用getFlightData,它将打印一组航班代码。但是,当在for循环中尝试相同操作时,数组flightsToSunnyCities将打印一组方括号,内有空白。在for循环迭代时,在for循环中打印此数字同样会打印空白

var data ScheduledFlight

func UnmarshalBodyToPointerFlight(Body []byte, welcome *ScheduledFlight) {
    err2 := json.Unmarshal(Body, &welcome)
    if err2 != nil {
        fmt.Println(err2)
        os.Exit(1)
    }
}

func GetFlightData(url string) *ScheduledFlight {
    res := FetchResponse(url)
    body := ResponseBodyToByte(res)
    UnmarshalBodyToPointerFlight(body, &data)
    return &data
}

func UnmarshalFlightStatsURL() []string {
    urlList := listOfURL()
    var flightsToSunnyCities []string
    for _, item := range urlList {

        var flightStats *ScheduledFlight = GetFlightData(item)
        var thisNumber string = flightStats.FlightNumber
        flightsToSunnyCities = append(flightsToSunnyCities, thisNumber)

    }
    fmt.Println(flightsToSunnyCities)
    return flightsToSunnyCities
}
我正在使用的结构如下所示:

type Welcome struct {
    ScheduledFlights []ScheduledFlight `json:"scheduledFlights"`
}

type ScheduledFlight struct {
    CarrierFSCode          string `json:"carrierFsCode"`
    FlightNumber           string `json:"flightNumber"`
    DepartureAirportFSCode string `json:"departureAirportFsCode"`
    ArrivalAirportFSCode   string `json:"arrivalAirportFsCode"`
}

我怀疑这个问题是由于
ScheduledFlights
属于
[]ScheduledFlights
类型而引起的,这需要加以解释,但是我不知道解决方案是什么。如果有人有任何建议,我们将不胜感激,谢谢。

您将下面的JSON输入解组的方式是错误的:

func UnmarshalBodyToPointerFlight(Body []byte, welcome *ScheduledFlight){
err2 := json.Unmarshal(Body, &welcome)
函数
unmarshalbodytopoinflight
获取一个指针
ScheduledFlight
,您希望将数据解组到该指针指向的位置。为此,您必须致电:

err2 := json.Unmarshal(Body, welcome)

按照您的操作方式,它会覆盖
welcome
指针(而不是它所指向的位置)并解组到新位置,因为您将指针传递给了指针。因此,您最终会将空字符串附加到数据中。

以下JSON输入的解组方式是错误的:

func UnmarshalBodyToPointerFlight(Body []byte, welcome *ScheduledFlight){
err2 := json.Unmarshal(Body, &welcome)
函数
unmarshalbodytopoinflight
获取一个指针
ScheduledFlight
,您希望将数据解组到该指针指向的位置。为此,您必须致电:

err2 := json.Unmarshal(Body, welcome)
按照您的操作方式,它会覆盖
welcome
指针(而不是它所指向的位置)并解组到新位置,因为您将指针传递给了指针。因此,最终会将空字符串附加到数据中