随笔 - 934, 文章 - 0, 评论 - 249, 阅读 - 345万

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

Go语言读取网上Json格式的天气预报数据例子

Posted on   蝈蝈俊  阅读(1691)  评论(0编辑  收藏  举报

天气预报接口使用的是:http://www.weather.com.cn/data/sk/101010100.html
这里的Json数据如下:
 

{
        "weatherinfo": {
              "city": "北京",
              "cityid": "101010100",
              "temp": "11",
              "WD": "北风",
              "WS": "4级",
              "SD": "23%",
              "WSE": "4",
              "time": "05:20",
              "isRadar": "1",
              "Radar": "JC_RADAR_AZ9010_JB"
       }
}



GO语言实现的代码:
package main
 
import(
    "encoding/json"
    "io/ioutil"
    "log"
    "net/http"
)
 
type WeatherInfoJson struct{
    Weatherinfo WeatherinfoObject
}
 
type WeatherinfoObject struct{
    City    string
    CityId  string
    Temp    string
    WD      string
    WS      string
    SD      string
    WSE     string
    Time    string
    IsRadar string
    Radar   string
}
 
func main(){
    log.SetFlags(log.LstdFlags|log.Lshortfile)
    resp,err:=http.Get("http://www.weather.com.cn/data/sk/101010100.html")
    if err!=nil{
        log.Fatal(err)
    }
 
    defer resp.Body.Close()
    input,err:=ioutil.ReadAll(resp.Body)
 
    var jsonWeather WeatherInfoJson
    json.Unmarshal(input,&jsonWeather)
    log.Printf("Results:%v\n",jsonWeather)
 
    log.Println(jsonWeather.Weatherinfo.City)
    log.Println(jsonWeather.Weatherinfo.WD)
 
    //ioutil.WriteFile("wsk101010100.html",input,0644)
}
 
JSON解析查找对应关系的业务逻辑:
https://github.com/astaxie/build-web-application-with-golang/blob/master/07.2.md
例如JSON的key是city,那么怎么找对应的字段呢?
  • 首先查找tag含有City的可导出的struct字段(首字母大写)
  • 其次查找字段名是city的导出字段
  • 最后查找类似City或者 CItY这样的除了首字母之外其他大小写不敏感的导出字段

聪明的你一定注意到了这一点:能够被赋值的字段必须是可导出字段(即首字母大写)。同时JSON解析的时候只会解析能找得到的字段,如果找不到的字段会被忽略,这样的一个好处是:当你接收到一个很大的JSON数据结构而你却只想获取其中的部分数据的时候,你只需将你想要的数据对应的字段名大写,即可轻松解决这个问题。

 
技术参考:
 
https://gist.github.com/border/775526
 
http://g.kehou.com/t1029846752.html

编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 记一次.NET内存居高不下排查解决与启示
点击右上角即可分享
微信分享提示