导航

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

Posted on 2013-03-18 05:45  蝈蝈俊  阅读(1668)  评论(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