如何在Golang中获得JSON响应 [英] How to get JSON response in Golang
问题描述
我试图从网上读取JSON数据,但是该代码返回空结果。
package main
importos我不确定我在这里做错了什么。
导入fmt
导入net / http
导入io / ioutil
导入encoding / json
类型曲目struct {
Toptracks [] Toptracks_info
}
类型Toptracks_info结构{
Track [] Track_info
Attr [] Attr_info
}
类型Track_info结构{
名称字符串
持续时间字符串
听众字符串
Mbid字符串
网址字符串
Streamable [] Streamable_info
艺术家[] Artist_info
Attr [] Track_attr_info
}
类型Attr_info结构{
国家字符串
页面字符串
每页字符串
TotalPages字符串
总字符串
}
类型Streamable_info结构{
文本字符串
Fulltrack字符串
}
类型Artist_info结构{
名称字符串
Mbid字符串
网址字符串
}
类型Track_attr_info结构{
等级字符串
}
func get_content (){
// json data
url:=http://ws.audioscrobbler.com/2.0/?method=geo.gettoptracks&api_key=c1572082105bd40d247836b5c1819623&format=json&country=荷兰
res,err:= http.Get(url)
if err!= nil {
panic(err.Error())
}
ody,err:= ioutil.ReadAll(res.Body)
if err!= nil {
panic(err.Error())
}
var data曲目
json.Unmarshal(body,& data)
fmt.Printf(结果:%v \ n,数据)
).bit.Exit(0)
}
func main(){
get_content()
}
理想的方法是不使用ioutil.ReadAll,而是使用解码器读者直接。这是一个很好的函数,它获取一个url并将其响应解码到一个目标
结构中。
var myClient =& http.Client {Timeout:10 * time.Second}
func getJson(url string,target interface {})error {
r,err:= myClient.Get(url)
if err!= nil {
return err
}
defer r.Body.Close()
return json。 NewDecoder(r.Body).Decode(target)
}
使用示例: p>
type Foo struct {
Bar字符串
}
func main(){
foo1:= new(Foo)//或者& Foo {}
getJson(http://example.com,foo1)
println(foo1.Bar)
//交替:
foo2:= Foo {}
getJson(http://example.com,& foo2)
println(foo2 .Bar)
}
您不应该使用默认的* http.Client结构作为这个答案最初的演示生产! (这是http.Get / etc调用的内容)。原因是默认客户端没有超时设置;如果远程服务器没有响应,那么你将会遇到糟糕的一天。
I'm trying read JSON data from web, but that code returns empty result. I'm not sure what I'm doing wrong here.
package main
import "os"
import "fmt"
import "net/http"
import "io/ioutil"
import "encoding/json"
type Tracks struct {
Toptracks []Toptracks_info
}
type Toptracks_info struct {
Track []Track_info
Attr []Attr_info
}
type Track_info struct {
Name string
Duration string
Listeners string
Mbid string
Url string
Streamable []Streamable_info
Artist []Artist_info
Attr []Track_attr_info
}
type Attr_info struct {
Country string
Page string
PerPage string
TotalPages string
Total string
}
type Streamable_info struct {
Text string
Fulltrack string
}
type Artist_info struct {
Name string
Mbid string
Url string
}
type Track_attr_info struct {
Rank string
}
func get_content() {
// json data
url := "http://ws.audioscrobbler.com/2.0/?method=geo.gettoptracks&api_key=c1572082105bd40d247836b5c1819623&format=json&country=Netherlands"
res, err := http.Get(url)
if err != nil {
panic(err.Error())
}
body, err := ioutil.ReadAll(res.Body)
if err != nil {
panic(err.Error())
}
var data Tracks
json.Unmarshal(body, &data)
fmt.Printf("Results: %v\n", data)
os.Exit(0)
}
func main() {
get_content()
}
The ideal way is not to use ioutil.ReadAll, but rather use a decoder on the reader directly. Here's a nice function that gets a url and decodes its response onto a target
structure.
var myClient = &http.Client{Timeout: 10 * time.Second}
func getJson(url string, target interface{}) error {
r, err := myClient.Get(url)
if err != nil {
return err
}
defer r.Body.Close()
return json.NewDecoder(r.Body).Decode(target)
}
Example use:
type Foo struct {
Bar string
}
func main() {
foo1 := new(Foo) // or &Foo{}
getJson("http://example.com", foo1)
println(foo1.Bar)
// alternately:
foo2 := Foo{}
getJson("http://example.com", &foo2)
println(foo2.Bar)
}
You should not be using the default *http.Client structure in production as this answer originally demonstrated! (Which is what http.Get/etc call to). The reason is that the default client has no timeout set; if the remote server is unresponsive, you're going to have a bad day.
这篇关于如何在Golang中获得JSON响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!