duanci1858 2019-02-26 20:35
浏览 50
已采纳

转到openweathermap预报返回类型

I am new to go and I am trying to build a little weather app using OpenWeatherMap and the go-package by briandowns.

I have no problem with reading the current weather but I have trouble processing the results of the forecast methods.

func main() {
    apiKey := "XXXX"
    w, err := owm.NewForecast("5", "C", "en", apiKey)
    if err != nil {
        log.Fatal(err)
    }
    w.DailyByName("London", 1)

    data := w.ForecastWeatherJson
    fmt.Println(data)
}

where the apiKey needs to be replaced by a valid one (which one can get for free upon registration).

My problem is to extract the information from the ForecastWeatherJson. It is defined as:

type ForecastWeatherJson interface {
    Decode(r io.Reader) error
}

in the forecast.go file.

With Decode defined as:

func (f *Forecast5WeatherData) Decode(r io.Reader) error {
    if err := json.NewDecoder(r).Decode(&f); err != nil {
        return err
    }
    return nil
}

in forecast5.go.

I really do not know where to start as I did not find a documented example which showed processing the data except for other languages (so I guess it s a go specific problem). I saw how it can be done in e.g. python but in the go case the return type is not clear to me.

Any hints or links to examples are appreciated.

  • 写回答

1条回答 默认 最新

  • douxiduan8344 2019-02-26 21:05
    关注

    Data that you need are already decoded in you w param, but you need to type assert to correct Weather type. In your case because you are using type=5 you should use owm.Forecast5WeatherData. Then your main will look like this.

    func main() {
        apiKey := "XXXX"
        w, err := owm.NewForecast("5", "C", "en", apiKey)
        if err != nil {
            log.Fatal(err)
        }
        w.DailyByName("London", 3)
    
        if val, ok := w.ForecastWeatherJson.(*owm.Forecast5WeatherData); ok {
    
            fmt.Println(val)
            fmt.Println(val.City)
            fmt.Println(val.Cnt)
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?