[gdut17@localhost http]$ go run getjson.go
{[{{WS0E9D8WN298 广州 CN 广州,广州,广东,中国 Asia/Shanghai +08:00} {阴 9 29} 2020-10-15T14:30:00+08:00}]}
地点:广州,温度:29,天气:阴,时间:2020-10-15T14:30:00+08:00
[gdut17@localhost http]$
package main
import (
"fmt"
"net/http"
"encoding/json"
"io/ioutil"
)
func main() {
url := "http://api.seniverse.com/v3/weather/now.json?key=0pyd8z7jouficcil&location=guangzhou&language=zh-Hans&unit=c"
GetJson(url)
}
func GetJson(url string) {
res, err := http.Get(url)
if err != nil {
fmt.Println("get err")
return
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
fmt.Println("read err")
return
}
jsonByte := []byte(body)
var w Weather
err = json.Unmarshal(jsonByte, &w)
if err != nil {
fmt.Println(err)
}
fmt.Println(w)
fmt.Printf("\n地点:%s,温度:%s,天气:%s,时间:%s\n",
w.Results[0].Location.Name,
w.Results[0].Now.Temperature,
w.Results[0].Now.Text,
w.Results[0].Last_update)
}
type Locat struct {
Id string `json:"id"`
Name string `json:"name"`
Country string `json:"country"`
Path string `json:"path"`
Timezone string `json:"timezone"`
Timezone_offset string `json:"timezone_offset"`
}
type Wea struct {
Text string `json:"text"`
Code string `json:"code"`
Temperature string `json:"temperature"`
}
type Member struct {
Location Locat `json:"location"`
Now Wea `json:"now"`
Last_update string `json:"last_update"`
}
type Weather struct {
Results []Member `json:member`
}
func test() {
jsonString := `
{
"results":
[
{
"location":
{
"id":"WT029G15ETRJ",
"name":"长沙",
"country":"CN",
"path":"长沙,长沙,湖南,中国",
"timezone":"Asia/Shanghai",
"timezone_offset":"+08:00"
},
"now":
{
"text":"小雨",
"code":"13",
"temperature":"16"
},
"last_update":"2020-10-15T13:50:08+08:00"
}
]
}`
jsonByte := []byte(jsonString)
var res Weather
err := json.Unmarshal(jsonByte, &res)
if err != nil {
fmt.Println(err)
}
fmt.Println(res)
fmt.Printf("%T\n",res)
}