golang读取json格式的天气预报

使用天气预报的接口:http://weather.china.xappengine.com/api?city=南宁 (找了好久才找到一个支持拼音的,不过好像小地方是没数据的)

访问得到json格式压缩的数据,格式化后


{
    "pub": "2013-06-29 22:59",
    "name": "南宁",
    "wind": {
        "chill": 81,
        "direction": 140,
        "speed": 7
    },
    "astronomy": {
        "sunrise": "6:05",
        "sunset": "19:34"
    },
    "atmosphere": {
        "humidity": 89,
        "visibility": 6.21,
        "pressure": 29.71,
        "rising": 1
    },
    "forecasts": [
        {
            "date": "2013-06-29",
            "day": 6,
            "code": 29,
            "text": "局部多云",
            "low": 26,
            "high": 32,
            "image_large": "http://weather.china.xappengine.com/static/w/img/d29.png",
            "image_small": "http://weather.china.xappengine.com/static/w/img/s29.png"
        },
        {
            "date": "2013-06-30",
            "day": 0,
            "code": 30,
            "text": "局部多云",
            "low": 25,
            "high": 33,
            "image_large": "http://weather.china.xappengine.com/static/w/img/d30.png",
            "image_small": "http://weather.china.xappengine.com/static/w/img/s30.png"
        },
        {
            "date": "2013-07-01",
            "day": 1,
            "code": 37,
            "text": "局部雷雨",
            "low": 24,
            "high": 32,
            "image_large": "http://weather.china.xappengine.com/static/w/img/d37.png",
            "image_small": "http://weather.china.xappengine.com/static/w/img/s37.png"
        },
        {
            "date": "2013-07-02",
            "day": 2,
            "code": 38,
            "text": "零星雷雨",
            "low": 25,
            "high": 32,
            "image_large": "http://weather.china.xappengine.com/static/w/img/d38.png",
            "image_small": "http://weather.china.xappengine.com/static/w/img/s38.png"
        },
        {
            "date": "2013-07-03",
            "day": 3,
            "code": 38,
            "text": "零星雷雨",
            "low": 25,
            "high": 32,
            "image_large": "http://weather.china.xappengine.com/static/w/img/d38.png",
            "image_small": "http://weather.china.xappengine.com/static/w/img/s38.png"
        }
    ]
}
GO语言内置的encoding/json标准库,Json.Unmarshal() 可以解析json数据

约定:json中的布尔值会解析为布尔值,数字(整数,浮点型)解析为float64,string解析为string,数组解析为接口数组,空值解析为nil。 这些字段在类型声明中必须都是以大写字母开头、可被导出的字段。

Json.Unmarshal()函数会根据一个约定的顺序查找目标结构中的字段,如果找到一个则进行匹配。当JSON数据中的数据结构和GO中的目标类型不匹配时,json.Unmarshal()函数在解码过程中会丢弃该字段。

 Json.Unmarshal()函数也支持读取未知的结构的json数据,允许使用map[string]interface{}和[]interface{}类型的值来分别存放未知结构的JSON对象或数组。

package main

import (
    "encoding/json"
	"io/ioutil"
	"net/http"
	"fmt"
)

//对应json天气数据源的结构,头字母大写
type WeatherInfoJson struct {
	Pub        string
	Name       string
	Wind       WindObject
	Astronomy  AstronomyObject
	Atmosphere AtmosphereObject
	Forecasts  []ForecastsObject
}

type WindObject struct {
	Chill     float64
	Direction float64
	Speed     float64
}

type AstronomyObject struct {
	Sunrise string
	Sunset  string
}

type AtmosphereObject struct {
	Humidity   float64
	Visibility float64
	Pressure   float64
	Rising     float64
}

type ForecastsObject struct {
	Date        string
	Day         float64
	Code        float64
	Text        string
	Low         float64
	High        float64
	Image_large string
	Image_small string
}

func GetWeather(city string) {

	str:="http://weather.china.xappengine.com/api?city="+city

	resp, err := http.Get(str)  //使用get方法访问
	if err != nil {
		return
	}

	defer resp.Body.Close()
	input, err1 := ioutil.ReadAll(resp.Body)    //读取流数据
	if err1 != nil {
		return
	}


	var jsonWeather WeatherInfoJson
	err2:=json.Unmarshal(input, &jsonWeather)   //解析json数据
	if err2 != nil {
		return
	}


	if len(jsonWeather.Name)!=0 {   //判断有无解析数据
	    for i := 0; i < 3; i++ {
	        fmt.Printf("-->地区:%s 时间:%s 温度:%d-%d 天气:%s 发布时间:%s\n", jsonWeather.Name,jsonWeather.Forecasts[i].Date,int(jsonWeather.Forecasts[i].Low),int(jsonWeather.Forecasts[i].High),jsonWeather.Forecasts[i].Text,jsonWeather.Pub)
	    }
    }
}

func main(){

    GetWeather("深圳")
    GetWeather("nanning")

}

运行结果如下


本文来自:开源中国博客

感谢作者:Mocos

查看原文:golang读取json格式的天气预报

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。